<!DOCTYPE html>

<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">

<title>module ActiveRecord::Associations::ClassMethods - Rails Framework Documentation</title>

<link type="text/css" media="screen" href="../../rdoc.css" rel="stylesheet">

<script type="text/javascript">
  var rdoc_rel_prefix = "../../";
</script>

<script type="text/javascript" charset="utf-8" src="../../js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/navigation.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/search_index.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/search.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/searcher.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/darkfish.js"></script>


<body id="top" class="module">
<nav id="metadata">
  <nav id="home-section" class="section">
  <h3 class="section-header">
    <a href="../../index.html">Home</a>
    <a href="../../table_of_contents.html#classes">Classes</a>
    <a href="../../table_of_contents.html#methods">Methods</a>
  </h3>
</nav>


  <nav id="search-section" class="section project-section" class="initially-hidden">
  <form action="#" method="get" accept-charset="utf-8">
    <h3 class="section-header">
      <input type="text" name="search" placeholder="Search" id="search-field"
             title="Type to search, Up and Down to navigate, Enter to load">
    </h3>
  </form>

  <ul id="search-results" class="initially-hidden"></ul>
</nav>


  <div id="file-metadata">
    <nav id="file-list-section" class="section">
  <h3 class="section-header">Defined In</h3>
  <ul>
    <li>/usr/local/lib/ruby/gems/1.9.1/gems/activerecord-3.2.7/lib/active_record/associations.rb
  </ul>
</nav>

    
  </div>

  <div id="class-metadata">
    
    
    
    <!-- Method Quickref -->
<nav id="method-list-section" class="section">
  <h3 class="section-header">Methods</h3>

  <ul class="link-list">
    
    <li><a href="#method-i-belongs_to">#belongs_to</a>
    
    <li><a href="#method-i-has_and_belongs_to_many">#has_and_belongs_to_many</a>
    
    <li><a href="#method-i-has_many">#has_many</a>
    
    <li><a href="#method-i-has_one">#has_one</a>
    
  </ul>
</nav>

  </div>

  <div id="project-metadata">
    <nav id="fileindex-section" class="section project-section">
  <h3 class="section-header">Pages</h3>

  <ul>
  
    <li class="file"><a href="../..//usr/local/lib/ruby/gems/1_9_1/gems/actionmailer-3_2_7/MIT-LICENSE.html">MIT-LICENSE</a>
  
    <li class="file"><a href="../..//usr/local/lib/ruby/gems/1_9_1/gems/actionmailer-3_2_7/README_rdoc.html">README</a>
  
    <li class="file"><a href="../..//usr/local/lib/ruby/gems/1_9_1/gems/actionpack-3_2_7/MIT-LICENSE.html">MIT-LICENSE</a>
  
    <li class="file"><a href="../..//usr/local/lib/ruby/gems/1_9_1/gems/actionpack-3_2_7/README_rdoc.html">README</a>
  
    <li class="file"><a href="../..//usr/local/lib/ruby/gems/1_9_1/gems/activemodel-3_2_7/MIT-LICENSE.html">MIT-LICENSE</a>
  
    <li class="file"><a href="../..//usr/local/lib/ruby/gems/1_9_1/gems/activemodel-3_2_7/README_rdoc.html">README</a>
  
    <li class="file"><a href="../..//usr/local/lib/ruby/gems/1_9_1/gems/activerecord-3_2_7/README_rdoc.html">README</a>
  
    <li class="file"><a href="../..//usr/local/lib/ruby/gems/1_9_1/gems/activeresource-3_2_7/README_rdoc.html">README</a>
  
    <li class="file"><a href="../..//usr/local/lib/ruby/gems/1_9_1/gems/activesupport-3_2_7/README_rdoc.html">README</a>
  
    <li class="file"><a href="../..//usr/local/lib/ruby/gems/1_9_1/gems/railties-3_2_7/README_rdoc.html">README</a>
  
    <li class="file"><a href="../../README_rdoc.html">README</a>
  
  </ul>
</nav>

    <nav id="classindex-section" class="section project-section">
  <h3 class="section-header">Class and Module Index</h3>

  <ul class="link-list">
  
    <li><a href="../../ActiveRecord.html">ActiveRecord</a>
  
    <li><a href="../../ActiveRecord/ActiveRecordError.html">ActiveRecord::ActiveRecordError</a>
  
    <li><a href="../../ActiveRecord/AdapterNotFound.html">ActiveRecord::AdapterNotFound</a>
  
    <li><a href="../../ActiveRecord/AdapterNotSpecified.html">ActiveRecord::AdapterNotSpecified</a>
  
    <li><a href="../../ActiveRecord/Aggregations.html">ActiveRecord::Aggregations</a>
  
    <li><a href="../../ActiveRecord/Aggregations/ClassMethods.html">ActiveRecord::Aggregations::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/AssociationTypeMismatch.html">ActiveRecord::AssociationTypeMismatch</a>
  
    <li><a href="../../ActiveRecord/Associations.html">ActiveRecord::Associations</a>
  
    <li><a href="../../ActiveRecord/Associations/ClassMethods.html">ActiveRecord::Associations::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/AttributeAssignment.html">ActiveRecord::AttributeAssignment</a>
  
    <li><a href="../../ActiveRecord/AttributeAssignment/ClassMethods.html">ActiveRecord::AttributeAssignment::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/AttributeAssignmentError.html">ActiveRecord::AttributeAssignmentError</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods.html">ActiveRecord::AttributeMethods</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/BeforeTypeCast.html">ActiveRecord::AttributeMethods::BeforeTypeCast</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/ClassMethods.html">ActiveRecord::AttributeMethods::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/DeprecatedUnderscoreRead.html">ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/DeprecatedUnderscoreRead/ClassMethods.html">ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/Dirty.html">ActiveRecord::AttributeMethods::Dirty</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/PrimaryKey.html">ActiveRecord::AttributeMethods::PrimaryKey</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/PrimaryKey/ClassMethods.html">ActiveRecord::AttributeMethods::PrimaryKey::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/Query.html">ActiveRecord::AttributeMethods::Query</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/Read.html">ActiveRecord::AttributeMethods::Read</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/Read/ClassMethods.html">ActiveRecord::AttributeMethods::Read::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/Serialization.html">ActiveRecord::AttributeMethods::Serialization</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/Serialization/Attribute.html">ActiveRecord::AttributeMethods::Serialization::Attribute</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/Serialization/ClassMethods.html">ActiveRecord::AttributeMethods::Serialization::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/TimeZoneConversion.html">ActiveRecord::AttributeMethods::TimeZoneConversion</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/TimeZoneConversion/ClassMethods.html">ActiveRecord::AttributeMethods::TimeZoneConversion::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/Write.html">ActiveRecord::AttributeMethods::Write</a>
  
    <li><a href="../../ActiveRecord/AttributeMethods/Write/ClassMethods.html">ActiveRecord::AttributeMethods::Write::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/AutosaveAssociation.html">ActiveRecord::AutosaveAssociation</a>
  
    <li><a href="../../ActiveRecord/AutosaveAssociation/ClassMethods.html">ActiveRecord::AutosaveAssociation::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/Base.html">ActiveRecord::Base</a>
  
    <li><a href="../../ActiveRecord/Batches.html">ActiveRecord::Batches</a>
  
    <li><a href="../../ActiveRecord/Calculations.html">ActiveRecord::Calculations</a>
  
    <li><a href="../../ActiveRecord/Callbacks.html">ActiveRecord::Callbacks</a>
  
    <li><a href="../../ActiveRecord/ConfigurationError.html">ActiveRecord::ConfigurationError</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/AbstractAdapter.html">ActiveRecord::ConnectionAdapters::AbstractAdapter</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/AbstractMysqlAdapter.html">ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/ConnectionHandler.html">ActiveRecord::ConnectionAdapters::ConnectionHandler</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/ConnectionManagement.html">ActiveRecord::ConnectionAdapters::ConnectionManagement</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/ConnectionPool.html">ActiveRecord::ConnectionAdapters::ConnectionPool</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/DatabaseLimits.html">ActiveRecord::ConnectionAdapters::DatabaseLimits</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/DatabaseStatements.html">ActiveRecord::ConnectionAdapters::DatabaseStatements</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/Mysql2Adapter.html">ActiveRecord::ConnectionAdapters::Mysql2Adapter</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/MysqlAdapter.html">ActiveRecord::ConnectionAdapters::MysqlAdapter</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/MysqlAdapter/StatementPool.html">ActiveRecord::ConnectionAdapters::MysqlAdapter::StatementPool</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/PostgreSQLAdapter.html">ActiveRecord::ConnectionAdapters::PostgreSQLAdapter</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/PostgreSQLAdapter/StatementPool.html">ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::StatementPool</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/PostgreSQLAdapter/TableDefinition.html">ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/PostgreSQLAdapter/Utils.html">ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/PostgreSQLColumn.html">ActiveRecord::ConnectionAdapters::PostgreSQLColumn</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/QueryCache.html">ActiveRecord::ConnectionAdapters::QueryCache</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/Quoting.html">ActiveRecord::ConnectionAdapters::Quoting</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/SQLiteAdapter.html">ActiveRecord::ConnectionAdapters::SQLiteAdapter</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/SQLiteAdapter/ExplainPrettyPrinter.html">ActiveRecord::ConnectionAdapters::SQLiteAdapter::ExplainPrettyPrinter</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/SQLiteAdapter/StatementPool.html">ActiveRecord::ConnectionAdapters::SQLiteAdapter::StatementPool</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/SQLiteAdapter/Version.html">ActiveRecord::ConnectionAdapters::SQLiteAdapter::Version</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/SchemaCache.html">ActiveRecord::ConnectionAdapters::SchemaCache</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/SchemaStatements.html">ActiveRecord::ConnectionAdapters::SchemaStatements</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/StatementPool.html">ActiveRecord::ConnectionAdapters::StatementPool</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/Table.html">ActiveRecord::ConnectionAdapters::Table</a>
  
    <li><a href="../../ActiveRecord/ConnectionAdapters/TableDefinition.html">ActiveRecord::ConnectionAdapters::TableDefinition</a>
  
    <li><a href="../../ActiveRecord/ConnectionNotEstablished.html">ActiveRecord::ConnectionNotEstablished</a>
  
    <li><a href="../../ActiveRecord/ConnectionTimeoutError.html">ActiveRecord::ConnectionTimeoutError</a>
  
    <li><a href="../../ActiveRecord/CounterCache.html">ActiveRecord::CounterCache</a>
  
    <li><a href="../../ActiveRecord/DangerousAttributeError.html">ActiveRecord::DangerousAttributeError</a>
  
    <li><a href="../../ActiveRecord/Delegation.html">ActiveRecord::Delegation</a>
  
    <li><a href="../../ActiveRecord/DynamicFinderMatch.html">ActiveRecord::DynamicFinderMatch</a>
  
    <li><a href="../../ActiveRecord/DynamicMatchers.html">ActiveRecord::DynamicMatchers</a>
  
    <li><a href="../../ActiveRecord/DynamicScopeMatch.html">ActiveRecord::DynamicScopeMatch</a>
  
    <li><a href="../../ActiveRecord/Explain.html">ActiveRecord::Explain</a>
  
    <li><a href="../../ActiveRecord/FinderMethods.html">ActiveRecord::FinderMethods</a>
  
    <li><a href="../../ActiveRecord/Fixtures.html">ActiveRecord::Fixtures</a>
  
    <li><a href="../../ActiveRecord/Fixtures/File.html">ActiveRecord::Fixtures::File</a>
  
    <li><a href="../../ActiveRecord/IdentityMap.html">ActiveRecord::IdentityMap</a>
  
    <li><a href="../../ActiveRecord/IdentityMap/Middleware.html">ActiveRecord::IdentityMap::Middleware</a>
  
    <li><a href="../../ActiveRecord/Inheritance.html">ActiveRecord::Inheritance</a>
  
    <li><a href="../../ActiveRecord/Inheritance/ClassMethods.html">ActiveRecord::Inheritance::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/Integration.html">ActiveRecord::Integration</a>
  
    <li><a href="../../ActiveRecord/InvalidForeignKey.html">ActiveRecord::InvalidForeignKey</a>
  
    <li><a href="../../ActiveRecord/IrreversibleMigration.html">ActiveRecord::IrreversibleMigration</a>
  
    <li><a href="../../ActiveRecord/Locking.html">ActiveRecord::Locking</a>
  
    <li><a href="../../ActiveRecord/Locking/Optimistic.html">ActiveRecord::Locking::Optimistic</a>
  
    <li><a href="../../ActiveRecord/Locking/Optimistic/ClassMethods.html">ActiveRecord::Locking::Optimistic::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/Locking/Pessimistic.html">ActiveRecord::Locking::Pessimistic</a>
  
    <li><a href="../../ActiveRecord/LogSubscriber.html">ActiveRecord::LogSubscriber</a>
  
    <li><a href="../../ActiveRecord/Migration.html">ActiveRecord::Migration</a>
  
    <li><a href="../../ActiveRecord/Migration/CommandRecorder.html">ActiveRecord::Migration::CommandRecorder</a>
  
    <li><a href="../../ActiveRecord/MigrationProxy.html">ActiveRecord::MigrationProxy</a>
  
    <li><a href="../../ActiveRecord/ModelSchema.html">ActiveRecord::ModelSchema</a>
  
    <li><a href="../../ActiveRecord/ModelSchema/ClassMethods.html">ActiveRecord::ModelSchema::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/MultiparameterAssignmentErrors.html">ActiveRecord::MultiparameterAssignmentErrors</a>
  
    <li><a href="../../ActiveRecord/NestedAttributes.html">ActiveRecord::NestedAttributes</a>
  
    <li><a href="../../ActiveRecord/NestedAttributes/ClassMethods.html">ActiveRecord::NestedAttributes::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/NestedAttributes/TooManyRecords.html">ActiveRecord::NestedAttributes::TooManyRecords</a>
  
    <li><a href="../../ActiveRecord/Observer.html">ActiveRecord::Observer</a>
  
    <li><a href="../../ActiveRecord/Persistence.html">ActiveRecord::Persistence</a>
  
    <li><a href="../../ActiveRecord/Persistence/ClassMethods.html">ActiveRecord::Persistence::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/PreparedStatementInvalid.html">ActiveRecord::PreparedStatementInvalid</a>
  
    <li><a href="../../ActiveRecord/QueryCache.html">ActiveRecord::QueryCache</a>
  
    <li><a href="../../ActiveRecord/QueryCache/ClassMethods.html">ActiveRecord::QueryCache::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/QueryMethods.html">ActiveRecord::QueryMethods</a>
  
    <li><a href="../../ActiveRecord/Querying.html">ActiveRecord::Querying</a>
  
    <li><a href="../../ActiveRecord/Railtie.html">ActiveRecord::Railtie</a>
  
    <li><a href="../../ActiveRecord/Railties.html">ActiveRecord::Railties</a>
  
    <li><a href="../../ActiveRecord/Railties/ControllerRuntime.html">ActiveRecord::Railties::ControllerRuntime</a>
  
    <li><a href="../../ActiveRecord/Railties/ControllerRuntime/ClassMethods.html">ActiveRecord::Railties::ControllerRuntime::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/ReadOnlyRecord.html">ActiveRecord::ReadOnlyRecord</a>
  
    <li><a href="../../ActiveRecord/ReadonlyAttributes.html">ActiveRecord::ReadonlyAttributes</a>
  
    <li><a href="../../ActiveRecord/ReadonlyAttributes/ClassMethods.html">ActiveRecord::ReadonlyAttributes::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/RecordInvalid.html">ActiveRecord::RecordInvalid</a>
  
    <li><a href="../../ActiveRecord/RecordNotFound.html">ActiveRecord::RecordNotFound</a>
  
    <li><a href="../../ActiveRecord/RecordNotSaved.html">ActiveRecord::RecordNotSaved</a>
  
    <li><a href="../../ActiveRecord/RecordNotUnique.html">ActiveRecord::RecordNotUnique</a>
  
    <li><a href="../../ActiveRecord/Reflection.html">ActiveRecord::Reflection</a>
  
    <li><a href="../../ActiveRecord/Reflection/ClassMethods.html">ActiveRecord::Reflection::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/Reflection/MacroReflection.html">ActiveRecord::Reflection::MacroReflection</a>
  
    <li><a href="../../ActiveRecord/Relation.html">ActiveRecord::Relation</a>
  
    <li><a href="../../ActiveRecord/Result.html">ActiveRecord::Result</a>
  
    <li><a href="../../ActiveRecord/Rollback.html">ActiveRecord::Rollback</a>
  
    <li><a href="../../ActiveRecord/Sanitization.html">ActiveRecord::Sanitization</a>
  
    <li><a href="../../ActiveRecord/Sanitization/ClassMethods.html">ActiveRecord::Sanitization::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/Schema.html">ActiveRecord::Schema</a>
  
    <li><a href="../../ActiveRecord/Scoping.html">ActiveRecord::Scoping</a>
  
    <li><a href="../../ActiveRecord/Scoping/ClassMethods.html">ActiveRecord::Scoping::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/Scoping/Default.html">ActiveRecord::Scoping::Default</a>
  
    <li><a href="../../ActiveRecord/Scoping/Default/ClassMethods.html">ActiveRecord::Scoping::Default::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/Scoping/Named.html">ActiveRecord::Scoping::Named</a>
  
    <li><a href="../../ActiveRecord/Scoping/Named/ClassMethods.html">ActiveRecord::Scoping::Named::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/Serialization.html">ActiveRecord::Serialization</a>
  
    <li><a href="../../ActiveRecord/SerializationTypeMismatch.html">ActiveRecord::SerializationTypeMismatch</a>
  
    <li><a href="../../ActiveRecord/SessionStore.html">ActiveRecord::SessionStore</a>
  
    <li><a href="../../ActiveRecord/SessionStore/Session.html">ActiveRecord::SessionStore::Session</a>
  
    <li><a href="../../ActiveRecord/SessionStore/SqlBypass.html">ActiveRecord::SessionStore::SqlBypass</a>
  
    <li><a href="../../ActiveRecord/SpawnMethods.html">ActiveRecord::SpawnMethods</a>
  
    <li><a href="../../ActiveRecord/StaleObjectError.html">ActiveRecord::StaleObjectError</a>
  
    <li><a href="../../ActiveRecord/StatementInvalid.html">ActiveRecord::StatementInvalid</a>
  
    <li><a href="../../ActiveRecord/Store.html">ActiveRecord::Store</a>
  
    <li><a href="../../ActiveRecord/Store/ClassMethods.html">ActiveRecord::Store::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/TestFixtures.html">ActiveRecord::TestFixtures</a>
  
    <li><a href="../../ActiveRecord/TestFixtures/ClassMethods.html">ActiveRecord::TestFixtures::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/ThrowResult.html">ActiveRecord::ThrowResult</a>
  
    <li><a href="../../ActiveRecord/Timestamp.html">ActiveRecord::Timestamp</a>
  
    <li><a href="../../ActiveRecord/Transactions.html">ActiveRecord::Transactions</a>
  
    <li><a href="../../ActiveRecord/Transactions/ClassMethods.html">ActiveRecord::Transactions::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/Translation.html">ActiveRecord::Translation</a>
  
    <li><a href="../../ActiveRecord/UnknownAttributeError.html">ActiveRecord::UnknownAttributeError</a>
  
    <li><a href="../../ActiveRecord/UnknownPrimaryKey.html">ActiveRecord::UnknownPrimaryKey</a>
  
    <li><a href="../../ActiveRecord/Validations.html">ActiveRecord::Validations</a>
  
    <li><a href="../../ActiveRecord/Validations/AssociatedValidator.html">ActiveRecord::Validations::AssociatedValidator</a>
  
    <li><a href="../../ActiveRecord/Validations/ClassMethods.html">ActiveRecord::Validations::ClassMethods</a>
  
    <li><a href="../../ActiveRecord/Validations/UniquenessValidator.html">ActiveRecord::Validations::UniquenessValidator</a>
  
    <li><a href="../../ActiveRecord/WrappedDatabaseException.html">ActiveRecord::WrappedDatabaseException</a>
  
    <li><a href="../../ActiveSupport.html">ActiveSupport</a>
  
    <li><a href="../../ActiveSupport/Autoload.html">ActiveSupport::Autoload</a>
  
    <li><a href="../../ActiveSupport/BacktraceCleaner.html">ActiveSupport::BacktraceCleaner</a>
  
    <li><a href="../../ActiveSupport/Base64.html">ActiveSupport::Base64</a>
  
    <li><a href="../../ActiveSupport/BasicObject.html">ActiveSupport::BasicObject</a>
  
    <li><a href="../../ActiveSupport/Benchmarkable.html">ActiveSupport::Benchmarkable</a>
  
    <li><a href="../../ActiveSupport/BufferedLogger.html">ActiveSupport::BufferedLogger</a>
  
    <li><a href="../../ActiveSupport/BufferedLogger/Severity.html">ActiveSupport::BufferedLogger::Severity</a>
  
    <li><a href="../../ActiveSupport/Cache.html">ActiveSupport::Cache</a>
  
    <li><a href="../../ActiveSupport/Cache/Entry.html">ActiveSupport::Cache::Entry</a>
  
    <li><a href="../../ActiveSupport/Cache/FileStore.html">ActiveSupport::Cache::FileStore</a>
  
    <li><a href="../../ActiveSupport/Cache/MemCacheStore.html">ActiveSupport::Cache::MemCacheStore</a>
  
    <li><a href="../../ActiveSupport/Cache/MemoryStore.html">ActiveSupport::Cache::MemoryStore</a>
  
    <li><a href="../../ActiveSupport/Cache/NullStore.html">ActiveSupport::Cache::NullStore</a>
  
    <li><a href="../../ActiveSupport/Cache/Store.html">ActiveSupport::Cache::Store</a>
  
    <li><a href="../../ActiveSupport/Cache/Strategy.html">ActiveSupport::Cache::Strategy</a>
  
    <li><a href="../../ActiveSupport/Cache/Strategy/LocalCache.html">ActiveSupport::Cache::Strategy::LocalCache</a>
  
    <li><a href="../../ActiveSupport/Cache/Strategy/LocalCache/LocalStore.html">ActiveSupport::Cache::Strategy::LocalCache::LocalStore</a>
  
    <li><a href="../../ActiveSupport/Callbacks.html">ActiveSupport::Callbacks</a>
  
    <li><a href="../../ActiveSupport/Callbacks/ClassMethods.html">ActiveSupport::Callbacks::ClassMethods</a>
  
    <li><a href="../../ActiveSupport/Concern.html">ActiveSupport::Concern</a>
  
    <li><a href="../../ActiveSupport/Configurable.html">ActiveSupport::Configurable</a>
  
    <li><a href="../../ActiveSupport/Configurable/ClassMethods.html">ActiveSupport::Configurable::ClassMethods</a>
  
    <li><a href="../../ActiveSupport/Configurable/Configuration.html">ActiveSupport::Configurable::Configuration</a>
  
    <li><a href="../../ActiveSupport/Dependencies.html">ActiveSupport::Dependencies</a>
  
    <li><a href="../../ActiveSupport/Dependencies/ClassCache.html">ActiveSupport::Dependencies::ClassCache</a>
  
    <li><a href="../../ActiveSupport/Dependencies/WatchStack.html">ActiveSupport::Dependencies::WatchStack</a>
  
    <li><a href="../../ActiveSupport/Deprecation.html">ActiveSupport::Deprecation</a>
  
    <li><a href="../../ActiveSupport/DescendantsTracker.html">ActiveSupport::DescendantsTracker</a>
  
    <li><a href="../../ActiveSupport/Duration.html">ActiveSupport::Duration</a>
  
    <li><a href="../../ActiveSupport/FileUpdateChecker.html">ActiveSupport::FileUpdateChecker</a>
  
    <li><a href="../../ActiveSupport/FileWatcher.html">ActiveSupport::FileWatcher</a>
  
    <li><a href="../../ActiveSupport/FileWatcher/Backend.html">ActiveSupport::FileWatcher::Backend</a>
  
    <li><a href="../../ActiveSupport/Gzip.html">ActiveSupport::Gzip</a>
  
    <li><a href="../../ActiveSupport/Gzip/Stream.html">ActiveSupport::Gzip::Stream</a>
  
    <li><a href="../../ActiveSupport/HashWithIndifferentAccess.html">ActiveSupport::HashWithIndifferentAccess</a>
  
    <li><a href="../../ActiveSupport/HashWithIndifferentAccess.html">ActiveSupport::HashWithIndifferentAccess</a>
  
    <li><a href="../../ActiveSupport/Inflector.html">ActiveSupport::Inflector</a>
  
    <li><a href="../../ActiveSupport/Inflector/Inflections.html">ActiveSupport::Inflector::Inflections</a>
  
    <li><a href="../../ActiveSupport/InheritableOptions.html">ActiveSupport::InheritableOptions</a>
  
    <li><a href="../../ActiveSupport/JSON.html">ActiveSupport::JSON</a>
  
    <li><a href="../../ActiveSupport/JSON/Encoding.html">ActiveSupport::JSON::Encoding</a>
  
    <li><a href="../../ActiveSupport/JSON/Encoding/CircularReferenceError.html">ActiveSupport::JSON::Encoding::CircularReferenceError</a>
  
    <li><a href="../../ActiveSupport/JSON/Encoding/Encoder.html">ActiveSupport::JSON::Encoding::Encoder</a>
  
    <li><a href="../../ActiveSupport/JSON/Variable.html">ActiveSupport::JSON::Variable</a>
  
    <li><a href="../../ActiveSupport/LogSubscriber.html">ActiveSupport::LogSubscriber</a>
  
    <li><a href="../../ActiveSupport/LogSubscriber/TestHelper.html">ActiveSupport::LogSubscriber::TestHelper</a>
  
    <li><a href="../../ActiveSupport/LogSubscriber/TestHelper/MockLogger.html">ActiveSupport::LogSubscriber::TestHelper::MockLogger</a>
  
    <li><a href="../../ActiveSupport/Memoizable.html">ActiveSupport::Memoizable</a>
  
    <li><a href="../../ActiveSupport/Memoizable/InstanceMethods.html">ActiveSupport::Memoizable::InstanceMethods</a>
  
    <li><a href="../../ActiveSupport/MessageEncryptor.html">ActiveSupport::MessageEncryptor</a>
  
    <li><a href="../../ActiveSupport/MessageEncryptor/InvalidMessage.html">ActiveSupport::MessageEncryptor::InvalidMessage</a>
  
    <li><a href="../../ActiveSupport/MessageVerifier.html">ActiveSupport::MessageVerifier</a>
  
    <li><a href="../../ActiveSupport/MessageVerifier/InvalidSignature.html">ActiveSupport::MessageVerifier::InvalidSignature</a>
  
    <li><a href="../../ActiveSupport/Multibyte.html">ActiveSupport::Multibyte</a>
  
    <li><a href="../../ActiveSupport/Multibyte/Chars.html">ActiveSupport::Multibyte::Chars</a>
  
    <li><a href="../../ActiveSupport/Multibyte/EncodingError.html">ActiveSupport::Multibyte::EncodingError</a>
  
    <li><a href="../../ActiveSupport/Multibyte/Unicode.html">ActiveSupport::Multibyte::Unicode</a>
  
    <li><a href="../../ActiveSupport/Multibyte/Unicode/Codepoint.html">ActiveSupport::Multibyte::Unicode::Codepoint</a>
  
    <li><a href="../../ActiveSupport/Multibyte/Unicode/UnicodeDatabase.html">ActiveSupport::Multibyte::Unicode::UnicodeDatabase</a>
  
    <li><a href="../../ActiveSupport/Notifications.html">ActiveSupport::Notifications</a>
  
    <li><a href="../../ActiveSupport/Notifications/Event.html">ActiveSupport::Notifications::Event</a>
  
    <li><a href="../../ActiveSupport/Notifications/Fanout.html">ActiveSupport::Notifications::Fanout</a>
  
    <li><a href="../../ActiveSupport/Notifications/Instrumenter.html">ActiveSupport::Notifications::Instrumenter</a>
  
    <li><a href="../../ActiveSupport/OrderedHash.html">ActiveSupport::OrderedHash</a>
  
    <li><a href="../../ActiveSupport/OrderedOptions.html">ActiveSupport::OrderedOptions</a>
  
    <li><a href="../../ActiveSupport/Railtie.html">ActiveSupport::Railtie</a>
  
    <li><a href="../../ActiveSupport/Rescuable.html">ActiveSupport::Rescuable</a>
  
    <li><a href="../../ActiveSupport/Rescuable/ClassMethods.html">ActiveSupport::Rescuable::ClassMethods</a>
  
    <li><a href="../../ActiveSupport/SafeBuffer.html">ActiveSupport::SafeBuffer</a>
  
    <li><a href="../../ActiveSupport/SafeBuffer/SafeConcatError.html">ActiveSupport::SafeBuffer::SafeConcatError</a>
  
    <li><a href="../../ActiveSupport/StringInquirer.html">ActiveSupport::StringInquirer</a>
  
    <li><a href="../../ActiveSupport/TaggedLogging.html">ActiveSupport::TaggedLogging</a>
  
    <li><a href="../../ActiveSupport/TestCase.html">ActiveSupport::TestCase</a>
  
    <li><a href="../../ActiveSupport/Testing.html">ActiveSupport::Testing</a>
  
    <li><a href="../../ActiveSupport/Testing/Assertions.html">ActiveSupport::Testing::Assertions</a>
  
    <li><a href="../../ActiveSupport/Testing/Declarative.html">ActiveSupport::Testing::Declarative</a>
  
    <li><a href="../../ActiveSupport/Testing/Isolation.html">ActiveSupport::Testing::Isolation</a>
  
    <li><a href="../../ActiveSupport/Testing/Isolation/Forking.html">ActiveSupport::Testing::Isolation::Forking</a>
  
    <li><a href="../../ActiveSupport/Testing/Isolation/MiniTest.html">ActiveSupport::Testing::Isolation::MiniTest</a>
  
    <li><a href="../../ActiveSupport/Testing/Isolation/Subprocess.html">ActiveSupport::Testing::Isolation::Subprocess</a>
  
    <li><a href="../../ActiveSupport/Testing/Isolation/TestUnit.html">ActiveSupport::Testing::Isolation::TestUnit</a>
  
    <li><a href="../../ActiveSupport/Testing/Pending.html">ActiveSupport::Testing::Pending</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance.html">ActiveSupport::Testing::Performance</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Benchmarker.html">ActiveSupport::Testing::Performance::Benchmarker</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/ForClassicTestUnit.html">ActiveSupport::Testing::Performance::ForClassicTestUnit</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/ForMiniTest.html">ActiveSupport::Testing::Performance::ForMiniTest</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics.html">ActiveSupport::Testing::Performance::Metrics</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/Amount.html">ActiveSupport::Testing::Performance::Metrics::Amount</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/Base.html">ActiveSupport::Testing::Performance::Metrics::Base</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/CpuTime.html">ActiveSupport::Testing::Performance::Metrics::CpuTime</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/DigitalInformationUnit.html">ActiveSupport::Testing::Performance::Metrics::DigitalInformationUnit</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/GcRuns.html">ActiveSupport::Testing::Performance::Metrics::GcRuns</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/GcTime.html">ActiveSupport::Testing::Performance::Metrics::GcTime</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/Memory.html">ActiveSupport::Testing::Performance::Metrics::Memory</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/Objects.html">ActiveSupport::Testing::Performance::Metrics::Objects</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/ProcessTime.html">ActiveSupport::Testing::Performance::Metrics::ProcessTime</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/Time.html">ActiveSupport::Testing::Performance::Metrics::Time</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/UserTime.html">ActiveSupport::Testing::Performance::Metrics::UserTime</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Metrics/WallTime.html">ActiveSupport::Testing::Performance::Metrics::WallTime</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Performer.html">ActiveSupport::Testing::Performance::Performer</a>
  
    <li><a href="../../ActiveSupport/Testing/Performance/Profiler.html">ActiveSupport::Testing::Performance::Profiler</a>
  
    <li><a href="../../ActiveSupport/Testing/ProxyTestResult.html">ActiveSupport::Testing::ProxyTestResult</a>
  
    <li><a href="../../ActiveSupport/Testing/RemoteError.html">ActiveSupport::Testing::RemoteError</a>
  
    <li><a href="../../ActiveSupport/Testing/SetupAndTeardown.html">ActiveSupport::Testing::SetupAndTeardown</a>
  
    <li><a href="../../ActiveSupport/Testing/SetupAndTeardown/ClassMethods.html">ActiveSupport::Testing::SetupAndTeardown::ClassMethods</a>
  
    <li><a href="../../ActiveSupport/Testing/SetupAndTeardown/ForClassicTestUnit.html">ActiveSupport::Testing::SetupAndTeardown::ForClassicTestUnit</a>
  
    <li><a href="../../ActiveSupport/Testing/SetupAndTeardown/ForMiniTest.html">ActiveSupport::Testing::SetupAndTeardown::ForMiniTest</a>
  
    <li><a href="../../ActiveSupport/TimeWithZone.html">ActiveSupport::TimeWithZone</a>
  
    <li><a href="../../ActiveSupport/TimeZone.html">ActiveSupport::TimeZone</a>
  
    <li><a href="../../ActiveSupport/XmlMini.html">ActiveSupport::XmlMini</a>
  
    <li><a href="../../ActiveSupport/XmlMini_LibXMLSAX.html">ActiveSupport::XmlMini_LibXMLSAX</a>
  
    <li><a href="../../ActiveSupport/XmlMini_LibXMLSAX/HashBuilder.html">ActiveSupport::XmlMini_LibXMLSAX::HashBuilder</a>
  
    <li><a href="../../ActiveSupport/XmlMini_NokogiriSAX.html">ActiveSupport::XmlMini_NokogiriSAX</a>
  
    <li><a href="../../ActiveSupport/XmlMini_NokogiriSAX/HashBuilder.html">ActiveSupport::XmlMini_NokogiriSAX::HashBuilder</a>
  
    <li><a href="../../ActionController.html">ActionController</a>
  
    <li><a href="../../ActionController/Base.html">ActionController::Base</a>
  
    <li><a href="../../ActionController/Caching.html">ActionController::Caching</a>
  
    <li><a href="../../ActionController/Caching/Actions.html">ActionController::Caching::Actions</a>
  
    <li><a href="../../ActionController/Caching/Actions/ActionCachePath.html">ActionController::Caching::Actions::ActionCachePath</a>
  
    <li><a href="../../ActionController/Caching/Actions/ClassMethods.html">ActionController::Caching::Actions::ClassMethods</a>
  
    <li><a href="../../ActionController/Caching/ConfigMethods.html">ActionController::Caching::ConfigMethods</a>
  
    <li><a href="../../ActionController/Caching/Fragments.html">ActionController::Caching::Fragments</a>
  
    <li><a href="../../ActionController/Caching/Pages.html">ActionController::Caching::Pages</a>
  
    <li><a href="../../ActionController/Caching/Pages/ClassMethods.html">ActionController::Caching::Pages::ClassMethods</a>
  
    <li><a href="../../ActionController/Caching/Sweeping.html">ActionController::Caching::Sweeping</a>
  
    <li><a href="../../ActionController/Compatibility.html">ActionController::Compatibility</a>
  
    <li><a href="../../ActionController/ConditionalGet.html">ActionController::ConditionalGet</a>
  
    <li><a href="../../ActionController/Cookies.html">ActionController::Cookies</a>
  
    <li><a href="../../ActionController/DataStreaming.html">ActionController::DataStreaming</a>
  
    <li><a href="../../ActionController/Flash.html">ActionController::Flash</a>
  
    <li><a href="../../ActionController/ForceSSL.html">ActionController::ForceSSL</a>
  
    <li><a href="../../ActionController/ForceSSL/ClassMethods.html">ActionController::ForceSSL::ClassMethods</a>
  
    <li><a href="../../ActionController/Head.html">ActionController::Head</a>
  
    <li><a href="../../ActionController/Helpers.html">ActionController::Helpers</a>
  
    <li><a href="../../ActionController/Helpers/ClassMethods.html">ActionController::Helpers::ClassMethods</a>
  
    <li><a href="../../ActionController/HideActions.html">ActionController::HideActions</a>
  
    <li><a href="../../ActionController/HideActions/ClassMethods.html">ActionController::HideActions::ClassMethods</a>
  
    <li><a href="../../ActionController/HttpAuthentication.html">ActionController::HttpAuthentication</a>
  
    <li><a href="../../ActionController/HttpAuthentication/Basic.html">ActionController::HttpAuthentication::Basic</a>
  
    <li><a href="../../ActionController/HttpAuthentication/Basic/ControllerMethods.html">ActionController::HttpAuthentication::Basic::ControllerMethods</a>
  
    <li><a href="../../ActionController/HttpAuthentication/Basic/ControllerMethods/ClassMethods.html">ActionController::HttpAuthentication::Basic::ControllerMethods::ClassMethods</a>
  
    <li><a href="../../ActionController/HttpAuthentication/Digest.html">ActionController::HttpAuthentication::Digest</a>
  
    <li><a href="../../ActionController/HttpAuthentication/Digest/ControllerMethods.html">ActionController::HttpAuthentication::Digest::ControllerMethods</a>
  
    <li><a href="../../ActionController/HttpAuthentication/Token.html">ActionController::HttpAuthentication::Token</a>
  
    <li><a href="../../ActionController/HttpAuthentication/Token/ControllerMethods.html">ActionController::HttpAuthentication::Token::ControllerMethods</a>
  
    <li><a href="../../ActionController/ImplicitRender.html">ActionController::ImplicitRender</a>
  
    <li><a href="../../ActionController/Instrumentation.html">ActionController::Instrumentation</a>
  
    <li><a href="../../ActionController/Instrumentation/ClassMethods.html">ActionController::Instrumentation::ClassMethods</a>
  
    <li><a href="../../ActionController/LogSubscriber.html">ActionController::LogSubscriber</a>
  
    <li><a href="../../ActionController/Metal.html">ActionController::Metal</a>
  
    <li><a href="../../ActionController/Middleware.html">ActionController::Middleware</a>
  
    <li><a href="../../ActionController/Middleware/ActionMiddleware.html">ActionController::Middleware::ActionMiddleware</a>
  
    <li><a href="../../ActionController/MimeResponds.html">ActionController::MimeResponds</a>
  
    <li><a href="../../ActionController/MimeResponds/ClassMethods.html">ActionController::MimeResponds::ClassMethods</a>
  
    <li><a href="../../ActionController/ParamsWrapper.html">ActionController::ParamsWrapper</a>
  
    <li><a href="../../ActionController/ParamsWrapper/ClassMethods.html">ActionController::ParamsWrapper::ClassMethods</a>
  
    <li><a href="../../ActionController/RackDelegation.html">ActionController::RackDelegation</a>
  
    <li><a href="../../ActionController/Railtie.html">ActionController::Railtie</a>
  
    <li><a href="../../ActionController/Railties.html">ActionController::Railties</a>
  
    <li><a href="../../ActionController/Railties/Paths.html">ActionController::Railties::Paths</a>
  
    <li><a href="../../ActionController/RecordIdentifier.html">ActionController::RecordIdentifier</a>
  
    <li><a href="../../ActionController/Redirecting.html">ActionController::Redirecting</a>
  
    <li><a href="../../ActionController/Renderers.html">ActionController::Renderers</a>
  
    <li><a href="../../ActionController/Renderers/All.html">ActionController::Renderers::All</a>
  
    <li><a href="../../ActionController/Renderers/ClassMethods.html">ActionController::Renderers::ClassMethods</a>
  
    <li><a href="../../ActionController/Rendering.html">ActionController::Rendering</a>
  
    <li><a href="../../ActionController/RequestForgeryProtection.html">ActionController::RequestForgeryProtection</a>
  
    <li><a href="../../ActionController/RequestForgeryProtection/ClassMethods.html">ActionController::RequestForgeryProtection::ClassMethods</a>
  
    <li><a href="../../ActionController/Rescue.html">ActionController::Rescue</a>
  
    <li><a href="../../ActionController/Responder.html">ActionController::Responder</a>
  
    <li><a href="../../ActionController/SessionManagement.html">ActionController::SessionManagement</a>
  
    <li><a href="../../ActionController/SessionManagement/ClassMethods.html">ActionController::SessionManagement::ClassMethods</a>
  
    <li><a href="../../ActionController/Streaming.html">ActionController::Streaming</a>
  
    <li><a href="../../ActionController/TemplateAssertions.html">ActionController::TemplateAssertions</a>
  
    <li><a href="../../ActionController/TestCase.html">ActionController::TestCase</a>
  
    <li><a href="../../ActionController/TestCase/Behavior.html">ActionController::TestCase::Behavior</a>
  
    <li><a href="../../ActionController/TestCase/Behavior/ClassMethods.html">ActionController::TestCase::Behavior::ClassMethods</a>
  
    <li><a href="../../ActionController/TestCase/RaiseActionExceptions.html">ActionController::TestCase::RaiseActionExceptions</a>
  
    <li><a href="../../ActionController/TestResponse.html">ActionController::TestResponse</a>
  
    <li><a href="../../ActionController/Testing.html">ActionController::Testing</a>
  
    <li><a href="../../ActionController/Testing/ClassMethods.html">ActionController::Testing::ClassMethods</a>
  
    <li><a href="../../ActionController/UrlFor.html">ActionController::UrlFor</a>
  
    <li><a href="../../ActionView.html">ActionView</a>
  
    <li><a href="../../ActionView/ActionView.html">ActionView::ActionView</a>
  
    <li><a href="../../ActionView/ActionView/ActionView.html">ActionView::ActionView::ActionView</a>
  
    <li><a href="../../ActionView/ActionView/ActionView/Base.html">ActionView::ActionView::ActionView::Base</a>
  
    <li><a href="../../ActionView/Base.html">ActionView::Base</a>
  
    <li><a href="../../ActionView/Context.html">ActionView::Context</a>
  
    <li><a href="../../ActionView/FileSystemResolver.html">ActionView::FileSystemResolver</a>
  
    <li><a href="../../ActionView/FixtureResolver.html">ActionView::FixtureResolver</a>
  
    <li><a href="../../ActionView/Helpers.html">ActionView::Helpers</a>
  
    <li><a href="../../ActionView/Helpers/ActiveModelHelper.html">ActionView::Helpers::ActiveModelHelper</a>
  
    <li><a href="../../ActionView/Helpers/ActiveModelInstanceTag.html">ActionView::Helpers::ActiveModelInstanceTag</a>
  
    <li><a href="../../ActionView/Helpers/AssetTagHelper.html">ActionView::Helpers::AssetTagHelper</a>
  
    <li><a href="../../ActionView/Helpers/AssetTagHelper/AssetIncludeTag.html">ActionView::Helpers::AssetTagHelper::AssetIncludeTag</a>
  
    <li><a href="../../ActionView/Helpers/AssetTagHelper/JavascriptIncludeTag.html">ActionView::Helpers::AssetTagHelper::JavascriptIncludeTag</a>
  
    <li><a href="../../ActionView/Helpers/AssetTagHelper/JavascriptTagHelpers.html">ActionView::Helpers::AssetTagHelper::JavascriptTagHelpers</a>
  
    <li><a href="../../ActionView/Helpers/AssetTagHelper/JavascriptTagHelpers/ClassMethods.html">ActionView::Helpers::AssetTagHelper::JavascriptTagHelpers::ClassMethods</a>
  
    <li><a href="../../ActionView/Helpers/AssetTagHelper/StylesheetIncludeTag.html">ActionView::Helpers::AssetTagHelper::StylesheetIncludeTag</a>
  
    <li><a href="../../ActionView/Helpers/AssetTagHelper/StylesheetTagHelpers.html">ActionView::Helpers::AssetTagHelper::StylesheetTagHelpers</a>
  
    <li><a href="../../ActionView/Helpers/AssetTagHelper/StylesheetTagHelpers/ClassMethods.html">ActionView::Helpers::AssetTagHelper::StylesheetTagHelpers::ClassMethods</a>
  
    <li><a href="../../ActionView/Helpers/AtomFeedHelper.html">ActionView::Helpers::AtomFeedHelper</a>
  
    <li><a href="../../ActionView/Helpers/AtomFeedHelper/AtomBuilder.html">ActionView::Helpers::AtomFeedHelper::AtomBuilder</a>
  
    <li><a href="../../ActionView/Helpers/AtomFeedHelper/AtomFeedBuilder.html">ActionView::Helpers::AtomFeedHelper::AtomFeedBuilder</a>
  
    <li><a href="../../ActionView/Helpers/CacheHelper.html">ActionView::Helpers::CacheHelper</a>
  
    <li><a href="../../ActionView/Helpers/CaptureHelper.html">ActionView::Helpers::CaptureHelper</a>
  
    <li><a href="../../ActionView/Helpers/CsrfHelper.html">ActionView::Helpers::CsrfHelper</a>
  
    <li><a href="../../ActionView/Helpers/DateHelper.html">ActionView::Helpers::DateHelper</a>
  
    <li><a href="../../ActionView/Helpers/DateHelperInstanceTag.html">ActionView::Helpers::DateHelperInstanceTag</a>
  
    <li><a href="../../ActionView/Helpers/DebugHelper.html">ActionView::Helpers::DebugHelper</a>
  
    <li><a href="../../ActionView/Helpers/FormBuilder.html">ActionView::Helpers::FormBuilder</a>
  
    <li><a href="../../ActionView/Helpers/FormHelper.html">ActionView::Helpers::FormHelper</a>
  
    <li><a href="../../ActionView/Helpers/FormOptionsHelper.html">ActionView::Helpers::FormOptionsHelper</a>
  
    <li><a href="../../ActionView/Helpers/FormTagHelper.html">ActionView::Helpers::FormTagHelper</a>
  
    <li><a href="../../ActionView/Helpers/InstanceTag.html">ActionView::Helpers::InstanceTag</a>
  
    <li><a href="../../ActionView/Helpers/JavaScriptHelper.html">ActionView::Helpers::JavaScriptHelper</a>
  
    <li><a href="../../ActionView/Helpers/NumberHelper.html">ActionView::Helpers::NumberHelper</a>
  
    <li><a href="../../ActionView/Helpers/NumberHelper/InvalidNumberError.html">ActionView::Helpers::NumberHelper::InvalidNumberError</a>
  
    <li><a href="../../ActionView/Helpers/OutputSafetyHelper.html">ActionView::Helpers::OutputSafetyHelper</a>
  
    <li><a href="../../ActionView/Helpers/RecordTagHelper.html">ActionView::Helpers::RecordTagHelper</a>
  
    <li><a href="../../ActionView/Helpers/RenderingHelper.html">ActionView::Helpers::RenderingHelper</a>
  
    <li><a href="../../ActionView/Helpers/SanitizeHelper.html">ActionView::Helpers::SanitizeHelper</a>
  
    <li><a href="../../ActionView/Helpers/TagHelper.html">ActionView::Helpers::TagHelper</a>
  
    <li><a href="../../ActionView/Helpers/TextHelper.html">ActionView::Helpers::TextHelper</a>
  
    <li><a href="../../ActionView/Helpers/TranslationHelper.html">ActionView::Helpers::TranslationHelper</a>
  
    <li><a href="../../ActionView/Helpers/UrlHelper.html">ActionView::Helpers::UrlHelper</a>
  
    <li><a href="../../ActionView/LogSubscriber.html">ActionView::LogSubscriber</a>
  
    <li><a href="../../ActionView/LookupContext.html">ActionView::LookupContext</a>
  
    <li><a href="../../ActionView/LookupContext/DetailsCache.html">ActionView::LookupContext::DetailsCache</a>
  
    <li><a href="../../ActionView/LookupContext/ViewPaths.html">ActionView::LookupContext::ViewPaths</a>
  
    <li><a href="../../ActionView/NullResolver.html">ActionView::NullResolver</a>
  
    <li><a href="../../ActionView/PartialRenderer.html">ActionView::PartialRenderer</a>
  
    <li><a href="../../ActionView/Railtie.html">ActionView::Railtie</a>
  
    <li><a href="../../ActionView/Renderer.html">ActionView::Renderer</a>
  
    <li><a href="../../ActionView/Resolver.html">ActionView::Resolver</a>
  
    <li><a href="../../ActionView/Resolver/Path.html">ActionView::Resolver::Path</a>
  
    <li><a href="../../ActionView/Template.html">ActionView::Template</a>
  
    <li><a href="../../ActionView/Template/Handlers.html">ActionView::Template::Handlers</a>
  
    <li><a href="../../ActionView/Template/Handlers/Builder.html">ActionView::Template::Handlers::Builder</a>
  
    <li><a href="../../ActionView/Template/Handlers/ERB.html">ActionView::Template::Handlers::ERB</a>
  
    <li><a href="../../ActionView/Template/Handlers/Erubis.html">ActionView::Template::Handlers::Erubis</a>
  
    <li><a href="../../ActionView/TestCase.html">ActionView::TestCase</a>
  
    <li><a href="../../ActionView/TestCase/Behavior.html">ActionView::TestCase::Behavior</a>
  
    <li><a href="../../ActionView/TestCase/Behavior/ClassMethods.html">ActionView::TestCase::Behavior::ClassMethods</a>
  
    <li><a href="../../ActionView/TestCase/Behavior/Locals.html">ActionView::TestCase::Behavior::Locals</a>
  
    <li><a href="../../ActionView/TestCase/TestController.html">ActionView::TestCase::TestController</a>
  
    <li><a href="../../ActiveModel.html">ActiveModel</a>
  
    <li><a href="../../ActiveModel/AttributeMethods.html">ActiveModel::AttributeMethods</a>
  
    <li><a href="../../ActiveModel/AttributeMethods/ClassMethods.html">ActiveModel::AttributeMethods::ClassMethods</a>
  
    <li><a href="../../ActiveModel/AttributeMethods/ClassMethods/AttributeMethodMatcher.html">ActiveModel::AttributeMethods::ClassMethods::AttributeMethodMatcher</a>
  
    <li><a href="../../ActiveModel/BlockValidator.html">ActiveModel::BlockValidator</a>
  
    <li><a href="../../ActiveModel/Callbacks.html">ActiveModel::Callbacks</a>
  
    <li><a href="../../ActiveModel/Conversion.html">ActiveModel::Conversion</a>
  
    <li><a href="../../ActiveModel/Dirty.html">ActiveModel::Dirty</a>
  
    <li><a href="../../ActiveModel/EachValidator.html">ActiveModel::EachValidator</a>
  
    <li><a href="../../ActiveModel/Errors.html">ActiveModel::Errors</a>
  
    <li><a href="../../ActiveModel/Lint.html">ActiveModel::Lint</a>
  
    <li><a href="../../ActiveModel/Lint/Tests.html">ActiveModel::Lint::Tests</a>
  
    <li><a href="../../ActiveModel/MassAssignmentSecurity.html">ActiveModel::MassAssignmentSecurity</a>
  
    <li><a href="../../ActiveModel/MassAssignmentSecurity/BlackList.html">ActiveModel::MassAssignmentSecurity::BlackList</a>
  
    <li><a href="../../ActiveModel/MassAssignmentSecurity/ClassMethods.html">ActiveModel::MassAssignmentSecurity::ClassMethods</a>
  
    <li><a href="../../ActiveModel/MassAssignmentSecurity/Error.html">ActiveModel::MassAssignmentSecurity::Error</a>
  
    <li><a href="../../ActiveModel/MassAssignmentSecurity/LoggerSanitizer.html">ActiveModel::MassAssignmentSecurity::LoggerSanitizer</a>
  
    <li><a href="../../ActiveModel/MassAssignmentSecurity/PermissionSet.html">ActiveModel::MassAssignmentSecurity::PermissionSet</a>
  
    <li><a href="../../ActiveModel/MassAssignmentSecurity/Sanitizer.html">ActiveModel::MassAssignmentSecurity::Sanitizer</a>
  
    <li><a href="../../ActiveModel/MassAssignmentSecurity/StrictSanitizer.html">ActiveModel::MassAssignmentSecurity::StrictSanitizer</a>
  
    <li><a href="../../ActiveModel/MassAssignmentSecurity/WhiteList.html">ActiveModel::MassAssignmentSecurity::WhiteList</a>
  
    <li><a href="../../ActiveModel/MissingAttributeError.html">ActiveModel::MissingAttributeError</a>
  
    <li><a href="../../ActiveModel/Name.html">ActiveModel::Name</a>
  
    <li><a href="../../ActiveModel/Naming.html">ActiveModel::Naming</a>
  
    <li><a href="../../ActiveModel/Observer.html">ActiveModel::Observer</a>
  
    <li><a href="../../ActiveModel/ObserverArray.html">ActiveModel::ObserverArray</a>
  
    <li><a href="../../ActiveModel/Observing.html">ActiveModel::Observing</a>
  
    <li><a href="../../ActiveModel/Observing/ClassMethods.html">ActiveModel::Observing::ClassMethods</a>
  
    <li><a href="../../ActiveModel/SecurePassword.html">ActiveModel::SecurePassword</a>
  
    <li><a href="../../ActiveModel/SecurePassword/ClassMethods.html">ActiveModel::SecurePassword::ClassMethods</a>
  
    <li><a href="../../ActiveModel/SecurePassword/InstanceMethodsOnActivation.html">ActiveModel::SecurePassword::InstanceMethodsOnActivation</a>
  
    <li><a href="../../ActiveModel/Serialization.html">ActiveModel::Serialization</a>
  
    <li><a href="../../ActiveModel/Serializers.html">ActiveModel::Serializers</a>
  
    <li><a href="../../ActiveModel/Serializers/JSON.html">ActiveModel::Serializers::JSON</a>
  
    <li><a href="../../ActiveModel/Serializers/Xml.html">ActiveModel::Serializers::Xml</a>
  
    <li><a href="../../ActiveModel/StrictValidationFailed.html">ActiveModel::StrictValidationFailed</a>
  
    <li><a href="../../ActiveModel/Translation.html">ActiveModel::Translation</a>
  
    <li><a href="../../ActiveModel/Validations.html">ActiveModel::Validations</a>
  
    <li><a href="../../ActiveModel/Validations/AcceptanceValidator.html">ActiveModel::Validations::AcceptanceValidator</a>
  
    <li><a href="../../ActiveModel/Validations/Callbacks.html">ActiveModel::Validations::Callbacks</a>
  
    <li><a href="../../ActiveModel/Validations/Callbacks/ClassMethods.html">ActiveModel::Validations::Callbacks::ClassMethods</a>
  
    <li><a href="../../ActiveModel/Validations/ClassMethods.html">ActiveModel::Validations::ClassMethods</a>
  
    <li><a href="../../ActiveModel/Validations/ConfirmationValidator.html">ActiveModel::Validations::ConfirmationValidator</a>
  
    <li><a href="../../ActiveModel/Validations/ExclusionValidator.html">ActiveModel::Validations::ExclusionValidator</a>
  
    <li><a href="../../ActiveModel/Validations/FormatValidator.html">ActiveModel::Validations::FormatValidator</a>
  
    <li><a href="../../ActiveModel/Validations/HelperMethods.html">ActiveModel::Validations::HelperMethods</a>
  
    <li><a href="../../ActiveModel/Validations/InclusionValidator.html">ActiveModel::Validations::InclusionValidator</a>
  
    <li><a href="../../ActiveModel/Validations/LengthValidator.html">ActiveModel::Validations::LengthValidator</a>
  
    <li><a href="../../ActiveModel/Validations/NumericalityValidator.html">ActiveModel::Validations::NumericalityValidator</a>
  
    <li><a href="../../ActiveModel/Validations/PresenceValidator.html">ActiveModel::Validations::PresenceValidator</a>
  
    <li><a href="../../ActiveModel/Validations/WithValidator.html">ActiveModel::Validations::WithValidator</a>
  
    <li><a href="../../ActiveModel/Validator.html">ActiveModel::Validator</a>
  
    <li><a href="../../ActiveResource.html">ActiveResource</a>
  
    <li><a href="../../ActiveResource/Base.html">ActiveResource::Base</a>
  
    <li><a href="../../ActiveResource/Connection.html">ActiveResource::Connection</a>
  
    <li><a href="../../ActiveResource/CustomMethods.html">ActiveResource::CustomMethods</a>
  
    <li><a href="../../ActiveResource/CustomMethods/ClassMethods.html">ActiveResource::CustomMethods::ClassMethods</a>
  
    <li><a href="../../ActiveResource/Errors.html">ActiveResource::Errors</a>
  
    <li><a href="../../ActiveResource/Formats.html">ActiveResource::Formats</a>
  
    <li><a href="../../ActiveResource/Formats/JsonFormat.html">ActiveResource::Formats::JsonFormat</a>
  
    <li><a href="../../ActiveResource/Formats/XmlFormat.html">ActiveResource::Formats::XmlFormat</a>
  
    <li><a href="../../ActiveResource/HttpMock.html">ActiveResource::HttpMock</a>
  
    <li><a href="../../ActiveResource/InvalidRequestError.html">ActiveResource::InvalidRequestError</a>
  
    <li><a href="../../ActiveResource/LogSubscriber.html">ActiveResource::LogSubscriber</a>
  
    <li><a href="../../ActiveResource/Observing.html">ActiveResource::Observing</a>
  
    <li><a href="../../ActiveResource/Railtie.html">ActiveResource::Railtie</a>
  
    <li><a href="../../ActiveResource/Request.html">ActiveResource::Request</a>
  
    <li><a href="../../ActiveResource/Response.html">ActiveResource::Response</a>
  
    <li><a href="../../ActiveResource/SSLError.html">ActiveResource::SSLError</a>
  
    <li><a href="../../ActiveResource/TimeoutError.html">ActiveResource::TimeoutError</a>
  
    <li><a href="../../ActiveResource/Validations.html">ActiveResource::Validations</a>
  
    <li><a href="../../HTML.html">HTML</a>
  
    <li><a href="../../HTML/FullSanitizer.html">HTML::FullSanitizer</a>
  
    <li><a href="../../HTML/LinkSanitizer.html">HTML::LinkSanitizer</a>
  
    <li><a href="../../HTML/Sanitizer.html">HTML::Sanitizer</a>
  
    <li><a href="../../HTML/Selector.html">HTML::Selector</a>
  
    <li><a href="../../HTML/Tag.html">HTML::Tag</a>
  
    <li><a href="../../HTML/WhiteListSanitizer.html">HTML::WhiteListSanitizer</a>
  
    <li><a href="../../Mysql.html">Mysql</a>
  
    <li><a href="../../Mysql/Result.html">Mysql::Result</a>
  
    <li><a href="../../Mysql/Stmt.html">Mysql::Stmt</a>
  
    <li><a href="../../Mysql/Time.html">Mysql::Time</a>
  
    <li><a href="../../Test.html">Test</a>
  
    <li><a href="../../Test/Unit.html">Test::Unit</a>
  
    <li><a href="../../Test/Unit/Collector.html">Test::Unit::Collector</a>
  
    <li><a href="../../Test/Unit/Collector/ObjectSpace.html">Test::Unit::Collector::ObjectSpace</a>
  
    <li><a href="../../I18n.html">I18n</a>
  
    <li><a href="../../I18n/ExceptionHandler.html">I18n::ExceptionHandler</a>
  
    <li><a href="../../I18n/Railtie.html">I18n::Railtie</a>
  
    <li><a href="../../Object.html">Object</a>
  
    <li><a href="../../ActiveSupport/HashWithIndifferentAccess.html">Object::HashWithIndifferentAccess</a>
  
    <li><a href="../../LoadError.html">Object::MissingSourceFile</a>
  
    <li><a href="../../ActionMailer.html">ActionMailer</a>
  
    <li><a href="../../ActionMailer/Base.html">ActionMailer::Base</a>
  
    <li><a href="../../ArJdbcMySQL.html">ArJdbcMySQL</a>
  
    <li><a href="../../ArJdbcMySQL/Error.html">ArJdbcMySQL::Error</a>
  
    <li><a href="../../ERB.html">ERB</a>
  
    <li><a href="../../ERB/Util.html">ERB::Util</a>
  
    <li><a href="../../LoadError.html">LoadError</a>
  
    <li><a href="../../LoadError.html">LoadError</a>
  
    <li><a href="../../Logger.html">Logger</a>
  
    <li><a href="../../Logger/SimpleFormatter.html">Logger::SimpleFormatter</a>
  
    <li><a href="../../Array.html">Array</a>
  
    <li><a href="../../Base64.html">Base64</a>
  
    <li><a href="../../Benchmark.html">Benchmark</a>
  
    <li><a href="../../BigDecimal.html">BigDecimal</a>
  
    <li><a href="../../Class.html">Class</a>
  
    <li><a href="../../Date.html">Date</a>
  
    <li><a href="../../DateTime.html">DateTime</a>
  
    <li><a href="../../Enumerable.html">Enumerable</a>
  
    <li><a href="../../FalseClass.html">FalseClass</a>
  
    <li><a href="../../File.html">File</a>
  
    <li><a href="../../Float.html">Float</a>
  
    <li><a href="../../Hash.html">Hash</a>
  
    <li><a href="../../Integer.html">Integer</a>
  
    <li><a href="../../Kernel.html">Kernel</a>
  
    <li><a href="../../Module.html">Module</a>
  
    <li><a href="../../NameError.html">NameError</a>
  
    <li><a href="../../NilClass.html">NilClass</a>
  
    <li><a href="../../Numeric.html">Numeric</a>
  
    <li><a href="../../Process.html">Process</a>
  
    <li><a href="../../QualifiedConstUtils.html">QualifiedConstUtils</a>
  
    <li><a href="../../Rails.html">Rails</a>
  
    <li><a href="../../Range.html">Range</a>
  
    <li><a href="../../Regexp.html">Regexp</a>
  
    <li><a href="../../String.html">String</a>
  
    <li><a href="../../Symbol.html">Symbol</a>
  
    <li><a href="../../Time.html">Time</a>
  
    <li><a href="../../TrueClass.html">TrueClass</a>
  
    <li><a href="../../URI.html">URI</a>
  
  </ul>
</nav>

  </div>
</nav>

<div id="documentation">
  <h1 class="module">module ActiveRecord::Associations::ClassMethods</h1>

  <div id="description" class="description">
    
<p><a href="../Associations.html">Associations</a> are a set of macro-like
class methods for tying objects together through foreign keys. They express
relationships like "Project has one Project Manager" or "Project belongs to
a Portfolio". Each macro adds a number of methods to the class which are
specialized according to the collection or association symbol and the
options hash. It works much the same way as Ruby's own <code>attr*</code>
methods.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Project</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span>              :<span class="ruby-identifier">portfolio</span>
  <span class="ruby-identifier">has_one</span>                 :<span class="ruby-identifier">project_manager</span>
  <span class="ruby-identifier">has_many</span>                :<span class="ruby-identifier">milestones</span>
  <span class="ruby-identifier">has_and_belongs_to_many</span> :<span class="ruby-identifier">categories</span>
<span class="ruby-keyword">end</span>
</pre>

<p>The project class now has the following methods (and more) to ease the
traversal and manipulation of its relationships:</p>
<ul><li>
<p><code>Project#portfolio, Project#portfolio=(portfolio),
Project#portfolio.nil?</code></p>
</li><li>
<p><code>Project#project_manager, Project#project_manager=(project_manager),
Project#project_manager.nil?,</code></p>
</li><li>
<p><code>Project#milestones.empty?, Project#milestones.size,
Project#milestones, Project#milestones&lt;&lt;(milestone),</code>
<code>Project#milestones.delete(milestone),
Project#milestones.find(milestone_id),
Project#milestones.all(options),</code> <code>Project#milestones.build,
Project#milestones.create</code></p>
</li><li>
<p><code>Project#categories.empty?, Project#categories.size,
Project#categories, Project#categories&lt;&lt;(category1),</code>
<code>Project#categories.delete(category1)</code></p>
</li></ul>

<h3 id="label-Overriding+generated+methods">Overriding generated methods</h3>

<p>Association methods are generated in a module that is included into the
model class, which allows you to easily override with your own methods and
call the original generated method with <code>super</code>. For example:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Car</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">owner</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">old_owner</span>
  <span class="ruby-keyword">def</span> <span class="ruby-identifier">owner=</span>(<span class="ruby-identifier">new_owner</span>)
    <span class="ruby-keyword">self</span>.<span class="ruby-identifier">old_owner</span> = <span class="ruby-keyword">self</span>.<span class="ruby-identifier">owner</span>
    <span class="ruby-keyword">super</span>
  <span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
</pre>

<p>If your model class is <code>Project</code>, the module is named
<code>Project::GeneratedFeatureMethods</code>. The GeneratedFeatureMethods
module is included in the model class immediately after the (anonymous)
generated attributes methods module, meaning an association will override
the methods for an attribute with the same name.</p>

<h3 id="label-A+word+of+warning">A word of warning</h3>

<p>Don’t create associations that have the same name as instance methods of
<code>ActiveRecord::Base</code>. Since the association adds a method with
that name to its model, it will override the inherited method and break
things. For instance, <code>attributes</code> and <code>connection</code>
would be bad choices for association names.</p>

<h2 id="label-Auto-generated+methods">Auto-generated methods</h2>

<h3 id="label-Singular+associations+%28one-to-one%29">Singular associations (one-to-one)</h3>

<pre>                                  |            |  belongs_to  |
generated methods                 | belongs_to | :polymorphic | has_one
----------------------------------+------------+--------------+---------
other                             |     X      |      X       |    X
other=(other)                     |     X      |      X       |    X
build_other(attributes={})        |     X      |              |    X
create_other(attributes={})       |     X      |              |    X
create_other!(attributes={})      |     X      |              |    X</pre>

<h3 id="label-Collection+associations+%28one-to-many+%2F+many-to-many%29">Collection associations (one-to-many / many-to-many)</h3>

<pre>                                  |       |          | has_many
generated methods                 | habtm | has_many | :through
----------------------------------+-------+----------+----------
others                            |   X   |    X     |    X
others=(other,other,...)          |   X   |    X     |    X
other_ids                         |   X   |    X     |    X
other_ids=(id,id,...)             |   X   |    X     |    X
others&lt;&lt;                          |   X   |    X     |    X
others.push                       |   X   |    X     |    X
others.concat                     |   X   |    X     |    X
others.build(attributes={})       |   X   |    X     |    X
others.create(attributes={})      |   X   |    X     |    X
others.create!(attributes={})     |   X   |    X     |    X
others.size                       |   X   |    X     |    X
others.length                     |   X   |    X     |    X
others.count                      |   X   |    X     |    X
others.sum(args*,&amp;block)          |   X   |    X     |    X
others.empty?                     |   X   |    X     |    X
others.clear                      |   X   |    X     |    X
others.delete(other,other,...)    |   X   |    X     |    X
others.delete_all                 |   X   |    X     |    X
others.destroy_all                |   X   |    X     |    X
others.find(*args)                |   X   |    X     |    X
others.exists?                    |   X   |    X     |    X
others.uniq                       |   X   |    X     |    X
others.reset                      |   X   |    X     |    X</pre>

<h2 id="label-Cardinality+and+associations">Cardinality and associations</h2>

<p>Active Record associations can be used to describe one-to-one, one-to-many
and many-to-many relationships between models. Each model uses an
association to describe its role in the relation. The
<code>belongs_to</code> association is always used in the model that has
the foreign key.</p>

<h3 id="label-One-to-one">One-to-one</h3>

<p>Use <code>has_one</code> in the base, and <code>belongs_to</code> in the
associated model.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Employee</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">office</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">class</span> <span class="ruby-constant">Office</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">employee</span>    <span class="ruby-comment"># foreign key - employee_id</span>
<span class="ruby-keyword">end</span>
</pre>

<h3 id="label-One-to-many">One-to-many</h3>

<p>Use <code>has_many</code> in the base, and <code>belongs_to</code> in the
associated model.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Manager</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">employees</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">class</span> <span class="ruby-constant">Employee</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">manager</span>     <span class="ruby-comment"># foreign key - manager_id</span>
<span class="ruby-keyword">end</span>
</pre>

<h3 id="label-Many-to-many">Many-to-many</h3>

<p>There are two ways to build a many-to-many relationship.</p>

<p>The first way uses a <code>has_many</code> association with the
<code>:through</code> option and a join model, so there are two stages of
associations.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Assignment</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">programmer</span>  <span class="ruby-comment"># foreign key - programmer_id</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">project</span>     <span class="ruby-comment"># foreign key - project_id</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">class</span> <span class="ruby-constant">Programmer</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">assignments</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">projects</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">assignments</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">class</span> <span class="ruby-constant">Project</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">assignments</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">programmers</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">assignments</span>
<span class="ruby-keyword">end</span>
</pre>

<p>For the second way, use <code>has_and_belongs_to_many</code> in both
models. This requires a join table that has no corresponding model or
primary key.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Programmer</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_and_belongs_to_many</span> :<span class="ruby-identifier">projects</span>       <span class="ruby-comment"># foreign keys in the join table</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">class</span> <span class="ruby-constant">Project</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_and_belongs_to_many</span> :<span class="ruby-identifier">programmers</span>    <span class="ruby-comment"># foreign keys in the join table</span>
<span class="ruby-keyword">end</span>
</pre>

<p>Choosing which way to build a many-to-many relationship is not always
simple. If you need to work with the relationship model as its own entity,
use <code>has_many :through</code>. Use
<code>has_and_belongs_to_many</code> when working with legacy schemas or
when you never work directly with the relationship itself.</p>

<h2 id="label-Is+it+a+belongs_to+or+has_one+association%3F">Is it a <code>belongs_to</code> or <code>has_one</code> association?</h2>

<p>Both express a 1-1 relationship. The difference is mostly where to place
the foreign key, which goes on the table for the class declaring the
<code>belongs_to</code> relationship.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">User</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-comment"># I reference an account.</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">account</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Account</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-comment"># One user references me.</span>
  <span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">user</span>
<span class="ruby-keyword">end</span>
</pre>

<p>The tables for these classes could look something like:</p>

<pre>CREATE TABLE users (
  id int(11) NOT NULL auto_increment,
  account_id int(11) default NULL,
  name varchar default NULL,
  PRIMARY KEY  (id)
)

CREATE TABLE accounts (
  id int(11) NOT NULL auto_increment,
  name varchar default NULL,
  PRIMARY KEY  (id)
)</pre>

<h2 id="label-Unsaved+objects+and+associations">Unsaved objects and associations</h2>

<p>You can manipulate objects and associations before they are saved to the
database, but there is some special behavior you should be aware of, mostly
involving the saving of associated objects.</p>

<p>You can set the :autosave option on a <code>has_one</code>,
<code>belongs_to</code>, <code>has_many</code>, or
<code>has_and_belongs_to_many</code> association. Setting it to
<code>true</code> will <em>always</em> save the members, whereas setting it
to <code>false</code> will <em>never</em> save the members. More details
about :autosave option is available at autosave_association.rb .</p>

<h3 id="label-One-to-one+associations">One-to-one associations</h3>
<ul><li>
<p>Assigning an object to a <code>has_one</code> association automatically
saves that object and the object being replaced (if there is one), in order
to update their foreign keys - except if the parent object is unsaved
(<code>new_record? == true</code>).</p>
</li><li>
<p>If either of these saves fail (due to one of the objects being invalid), an
<code>ActiveRecord::RecordNotSaved</code> exception is raised and the
assignment is cancelled.</p>
</li><li>
<p>If you wish to assign an object to a <code>has_one</code> association
without saving it, use the <code>build_association</code> method
(documented below). The object being replaced will still be saved to update
its foreign key.</p>
</li><li>
<p>Assigning an object to a <code>belongs_to</code> association does not save
the object, since the foreign key field belongs on the parent. It does not
save the parent either.</p>
</li></ul>

<h3 id="label-Collections">Collections</h3>
<ul><li>
<p>Adding an object to a collection (<code>has_many</code> or
<code>has_and_belongs_to_many</code>) automatically saves that object,
except if the parent object (the owner of the collection) is not yet stored
in the database.</p>
</li><li>
<p>If saving any of the objects being added to a collection (via
<code>push</code> or similar) fails, then <code>push</code> returns
<code>false</code>.</p>
</li><li>
<p>If saving fails while replacing the collection (via
<code>association=</code>), an <code>ActiveRecord::RecordNotSaved</code>
exception is raised and the assignment is cancelled.</p>
</li><li>
<p>You can add an object to a collection without automatically saving it by
using the <code>collection.build</code> method (documented below).</p>
</li><li>
<p>All unsaved (<code>new_record? == true</code>) members of the collection
are automatically saved when the parent is saved.</p>
</li></ul>

<h3 id="label-Association+callbacks">Association callbacks</h3>

<p>Similar to the normal callbacks that hook into the life cycle of an Active
Record object, you can also define callbacks that get triggered when you
add an object to or remove an object from an association collection.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Project</span>
  <span class="ruby-identifier">has_and_belongs_to_many</span> :<span class="ruby-identifier">developers</span>, :<span class="ruby-identifier">after_add</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">evaluate_velocity</span>

  <span class="ruby-keyword">def</span> <span class="ruby-identifier">evaluate_velocity</span>(<span class="ruby-identifier">developer</span>)
    <span class="ruby-operator">...</span>
  <span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
</pre>

<p>It’s possible to stack callbacks by passing them as an array. Example:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Project</span>
  <span class="ruby-identifier">has_and_belongs_to_many</span> :<span class="ruby-identifier">developers</span>,
                          :<span class="ruby-identifier">after_add</span> =<span class="ruby-operator">&gt;</span> [:<span class="ruby-identifier">evaluate_velocity</span>, <span class="ruby-constant">Proc</span>.<span class="ruby-identifier">new</span> { <span class="ruby-operator">|</span><span class="ruby-identifier">p</span>, <span class="ruby-identifier">d</span><span class="ruby-operator">|</span> <span class="ruby-identifier">p</span>.<span class="ruby-identifier">shipping_date</span> = <span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span>}]
<span class="ruby-keyword">end</span>
</pre>

<p>Possible callbacks are: <code>before_add</code>, <code>after_add</code>,
<code>before_remove</code> and <code>after_remove</code>.</p>

<p>Should any of the <code>before_add</code> callbacks throw an exception, the
object does not get added to the collection. Same with the
<code>before_remove</code> callbacks; if an exception is thrown the object
doesn’t get removed.</p>

<h3 id="label-Association+extensions">Association extensions</h3>

<p>The proxy objects that control the access to associations can be extended
through anonymous modules. This is especially beneficial for adding new
finders, creators, and other factory-type methods that are only used as
part of this association.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Account</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">people</span> <span class="ruby-keyword">do</span>
    <span class="ruby-keyword">def</span> <span class="ruby-identifier">find_or_create_by_name</span>(<span class="ruby-identifier">name</span>)
      <span class="ruby-identifier">first_name</span>, <span class="ruby-identifier">last_name</span> = <span class="ruby-identifier">name</span>.<span class="ruby-identifier">split</span>(<span class="ruby-string">&quot; &quot;</span>, <span class="ruby-value">2</span>)
      <span class="ruby-identifier">find_or_create_by_first_name_and_last_name</span>(<span class="ruby-identifier">first_name</span>, <span class="ruby-identifier">last_name</span>)
    <span class="ruby-keyword">end</span>
  <span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>

<span class="ruby-identifier">person</span> = <span class="ruby-constant">Account</span>.<span class="ruby-identifier">first</span>.<span class="ruby-identifier">people</span>.<span class="ruby-identifier">find_or_create_by_name</span>(<span class="ruby-string">&quot;David Heinemeier Hansson&quot;</span>)
<span class="ruby-identifier">person</span>.<span class="ruby-identifier">first_name</span> <span class="ruby-comment"># =&gt; &quot;David&quot;</span>
<span class="ruby-identifier">person</span>.<span class="ruby-identifier">last_name</span>  <span class="ruby-comment"># =&gt; &quot;Heinemeier Hansson&quot;</span>
</pre>

<p>If you need to share the same extensions between many associations, you can
use a named extension module.</p>

<pre class="ruby"><span class="ruby-keyword">module</span> <span class="ruby-constant">FindOrCreateByNameExtension</span>
  <span class="ruby-keyword">def</span> <span class="ruby-identifier">find_or_create_by_name</span>(<span class="ruby-identifier">name</span>)
    <span class="ruby-identifier">first_name</span>, <span class="ruby-identifier">last_name</span> = <span class="ruby-identifier">name</span>.<span class="ruby-identifier">split</span>(<span class="ruby-string">&quot; &quot;</span>, <span class="ruby-value">2</span>)
    <span class="ruby-identifier">find_or_create_by_first_name_and_last_name</span>(<span class="ruby-identifier">first_name</span>, <span class="ruby-identifier">last_name</span>)
  <span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Account</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">people</span>, :<span class="ruby-identifier">extend</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-constant">FindOrCreateByNameExtension</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Company</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">people</span>, :<span class="ruby-identifier">extend</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-constant">FindOrCreateByNameExtension</span>
<span class="ruby-keyword">end</span>
</pre>

<p>If you need to use multiple named extension modules, you can specify an
array of modules with the <code>:extend</code> option. In the case of name
conflicts between methods in the modules, methods in modules later in the
array supercede those earlier in the array.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Account</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">people</span>, :<span class="ruby-identifier">extend</span> =<span class="ruby-operator">&gt;</span> [<span class="ruby-constant">FindOrCreateByNameExtension</span>, <span class="ruby-constant">FindRecentExtension</span>]
<span class="ruby-keyword">end</span>
</pre>

<p>Some extensions can only be made to work with knowledge of the
association’s internals. Extensions can access relevant state using the
following methods (where <code>items</code> is the name of the
association):</p>
<ul><li>
<p><code>record.association(:items).owner</code> - Returns the object the
association is part of.</p>
</li><li>
<p><code>record.association(:items).reflection</code> - Returns the reflection
object that describes the association.</p>
</li><li>
<p><code>record.association(:items).target</code> - Returns the associated
object for <code>belongs_to</code> and <code>has_one</code>, or the
collection of associated objects for <code>has_many</code> and
<code>has_and_belongs_to_many</code>.</p>
</li></ul>

<p>However, inside the actual extension code, you will not have access to the
<code>record</code> as above. In this case, you can access
<code>proxy_association</code>. For example,
<code>record.association(:items)</code> and
<code>record.items.proxy_association</code> will return the same object,
allowing you to make calls like <code>proxy_association.owner</code> inside
association extensions.</p>

<h3 id="label-Association+Join+Models">Association Join Models</h3>

<p>Has Many associations can be configured with the <code>:through</code>
option to use an explicit join model to retrieve the data. This operates
similarly to a <code>has_and_belongs_to_many</code> association. The
advantage is that you’re able to add validations, callbacks, and extra
attributes on the join model. Consider the following schema:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Author</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">authorships</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">books</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">authorships</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Authorship</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">author</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">book</span>
<span class="ruby-keyword">end</span>

<span class="ruby-ivar">@author</span> = <span class="ruby-constant">Author</span>.<span class="ruby-identifier">first</span>
<span class="ruby-ivar">@author</span>.<span class="ruby-identifier">authorships</span>.<span class="ruby-identifier">collect</span> { <span class="ruby-operator">|</span><span class="ruby-identifier">a</span><span class="ruby-operator">|</span> <span class="ruby-identifier">a</span>.<span class="ruby-identifier">book</span> } <span class="ruby-comment"># selects all books that the author's authorships belong to</span>
<span class="ruby-ivar">@author</span>.<span class="ruby-identifier">books</span>                              <span class="ruby-comment"># selects all books by using the Authorship join model</span>
</pre>

<p>You can also go through a <code>has_many</code> association on the join
model:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Firm</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span>   :<span class="ruby-identifier">clients</span>
  <span class="ruby-identifier">has_many</span>   :<span class="ruby-identifier">invoices</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">clients</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Client</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">firm</span>
  <span class="ruby-identifier">has_many</span>   :<span class="ruby-identifier">invoices</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Invoice</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">client</span>
<span class="ruby-keyword">end</span>

<span class="ruby-ivar">@firm</span> = <span class="ruby-constant">Firm</span>.<span class="ruby-identifier">first</span>
<span class="ruby-ivar">@firm</span>.<span class="ruby-identifier">clients</span>.<span class="ruby-identifier">collect</span> { <span class="ruby-operator">|</span><span class="ruby-identifier">c</span><span class="ruby-operator">|</span> <span class="ruby-identifier">c</span>.<span class="ruby-identifier">invoices</span> }.<span class="ruby-identifier">flatten</span> <span class="ruby-comment"># select all invoices for all clients of the firm</span>
<span class="ruby-ivar">@firm</span>.<span class="ruby-identifier">invoices</span>                                   <span class="ruby-comment"># selects all invoices by going through the Client join model</span>
</pre>

<p>Similarly you can go through a <code>has_one</code> association on the join
model:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Group</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span>   :<span class="ruby-identifier">users</span>
  <span class="ruby-identifier">has_many</span>   :<span class="ruby-identifier">avatars</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">users</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">User</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">group</span>
  <span class="ruby-identifier">has_one</span>    :<span class="ruby-identifier">avatar</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Avatar</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">user</span>
<span class="ruby-keyword">end</span>

<span class="ruby-ivar">@group</span> = <span class="ruby-constant">Group</span>.<span class="ruby-identifier">first</span>
<span class="ruby-ivar">@group</span>.<span class="ruby-identifier">users</span>.<span class="ruby-identifier">collect</span> { <span class="ruby-operator">|</span><span class="ruby-identifier">u</span><span class="ruby-operator">|</span> <span class="ruby-identifier">u</span>.<span class="ruby-identifier">avatar</span> }.<span class="ruby-identifier">flatten</span> <span class="ruby-comment"># select all avatars for all users in the group</span>
<span class="ruby-ivar">@group</span>.<span class="ruby-identifier">avatars</span>                                <span class="ruby-comment"># selects all avatars by going through the User join model.</span>
</pre>

<p>An important caveat with going through <code>has_one</code> or
<code>has_many</code> associations on the join model is that these
associations are <strong>read-only</strong>. For example, the following
would not work following the previous example:</p>

<pre>@group.avatars &lt;&lt; Avatar.new   # this would work if User belonged_to Avatar rather than the other way around
@group.avatars.delete(@group.avatars.last)  # so would this</pre>

<p>If you are using a <code>belongs_to</code> on the join model, it is a good
idea to set the <code>:inverse_of</code> option on the
<code>belongs_to</code>, which will mean that the following example works
correctly (where <code>tags</code> is a <code>has_many</code>
<code>:through</code> association):</p>

<pre class="ruby"><span class="ruby-ivar">@post</span> = <span class="ruby-constant">Post</span>.<span class="ruby-identifier">first</span>
<span class="ruby-ivar">@tag</span> = <span class="ruby-ivar">@post</span>.<span class="ruby-identifier">tags</span>.<span class="ruby-identifier">build</span> :<span class="ruby-identifier">name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;ruby&quot;</span>
<span class="ruby-ivar">@tag</span>.<span class="ruby-identifier">save</span>
</pre>

<p>The last line ought to save the through record (a <code>Taggable</code>).
This will only work if the <code>:inverse_of</code> is set:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Taggable</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">post</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">tag</span>, :<span class="ruby-identifier">inverse_of</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">taggings</span>
<span class="ruby-keyword">end</span>
</pre>

<h3 id="label-Nested+Associations">Nested <a href="../Associations.html">Associations</a></h3>

<p>You can actually specify <strong>any</strong> association with the
<code>:through</code> option, including an association which has a
<code>:through</code> option itself. For example:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Author</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">posts</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">comments</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">posts</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">commenters</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">comments</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Post</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">comments</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Comment</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">commenter</span>
<span class="ruby-keyword">end</span>

<span class="ruby-ivar">@author</span> = <span class="ruby-constant">Author</span>.<span class="ruby-identifier">first</span>
<span class="ruby-ivar">@author</span>.<span class="ruby-identifier">commenters</span> <span class="ruby-comment"># =&gt; People who commented on posts written by the author</span>
</pre>

<p>An equivalent way of setting up this association this would be:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Author</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">posts</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">commenters</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">posts</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Post</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">comments</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">commenters</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">comments</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Comment</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">commenter</span>
<span class="ruby-keyword">end</span>
</pre>

<p>When using nested association, you will not be able to modify the
association because there is not enough information to know what
modification to make. For example, if you tried to add a
<code>Commenter</code> in the example above, there would be no way to tell
how to set up the intermediate <code>Post</code> and <code>Comment</code>
objects.</p>

<h3 id="label-Polymorphic+Associations">Polymorphic <a href="../Associations.html">Associations</a></h3>

<p>Polymorphic associations on models are not restricted on what types of
models they can be associated with. Rather, they specify an interface that
a <code>has_many</code> association must adhere to.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Asset</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">attachable</span>, :<span class="ruby-identifier">polymorphic</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Post</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">assets</span>, :<span class="ruby-identifier">as</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">attachable</span>         <span class="ruby-comment"># The :as option specifies the polymorphic interface to use.</span>
<span class="ruby-keyword">end</span>

<span class="ruby-ivar">@asset</span>.<span class="ruby-identifier">attachable</span> = <span class="ruby-ivar">@post</span>
</pre>

<p>This works by using a type column in addition to a foreign key to specify
the associated record. In the Asset example, you’d need an
<code>attachable_id</code> integer column and an
<code>attachable_type</code> string column.</p>

<p>Using polymorphic associations in combination with single table inheritance
(STI) is a little tricky. In order for the associations to work as
expected, ensure that you store the base model for the STI models in the
type column of the polymorphic association. To continue with the asset
example above, suppose there are guest posts and member posts that use the
posts table for STI. In this case, there must be a <code>type</code> column
in the posts table.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Asset</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">attachable</span>, :<span class="ruby-identifier">polymorphic</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>

  <span class="ruby-keyword">def</span> <span class="ruby-identifier">attachable_type=</span>(<span class="ruby-identifier">sType</span>)
     <span class="ruby-keyword">super</span>(<span class="ruby-identifier">sType</span>.<span class="ruby-identifier">to_s</span>.<span class="ruby-identifier">classify</span>.<span class="ruby-identifier">constantize</span>.<span class="ruby-identifier">base_class</span>.<span class="ruby-identifier">to_s</span>)
  <span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Post</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-comment"># because we store &quot;Post&quot; in attachable_type now :dependent =&gt; :destroy will work</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">assets</span>, :<span class="ruby-identifier">as</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">attachable</span>, :<span class="ruby-identifier">dependent</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">destroy</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">GuestPost</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">Post</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">MemberPost</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">Post</span>
<span class="ruby-keyword">end</span>
</pre>

<h2 id="label-Caching">Caching</h2>

<p>All of the methods are built on a simple caching principle that will keep
the result of the last query around unless specifically instructed not to.
The cache is even shared across methods to make it even cheaper to use the
macro-added methods without worrying too much about performance at the
first go.</p>

<pre>project.milestones             # fetches milestones from the database
project.milestones.size        # uses the milestone cache
project.milestones.empty?      # uses the milestone cache
project.milestones(true).size  # fetches milestones from the database
project.milestones             # uses the milestone cache</pre>

<h2 id="label-Eager+loading+of+associations">Eager loading of associations</h2>

<p>Eager loading is a way to find objects of a certain class and a number of
named associations. This is one of the easiest ways of to prevent the
dreaded 1+N problem in which fetching 100 posts that each need to display
their author triggers 101 database queries. Through the use of eager
loading, the 101 queries can be reduced to 2.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Post</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">author</span>
  <span class="ruby-identifier">has_many</span>   :<span class="ruby-identifier">comments</span>
<span class="ruby-keyword">end</span>
</pre>

<p>Consider the following loop using the class above:</p>

<pre class="ruby"><span class="ruby-constant">Post</span>.<span class="ruby-identifier">all</span>.<span class="ruby-identifier">each</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">post</span><span class="ruby-operator">|</span>
  <span class="ruby-identifier">puts</span> <span class="ruby-string">&quot;Post:            &quot;</span> <span class="ruby-operator">+</span> <span class="ruby-identifier">post</span>.<span class="ruby-identifier">title</span>
  <span class="ruby-identifier">puts</span> <span class="ruby-string">&quot;Written by:      &quot;</span> <span class="ruby-operator">+</span> <span class="ruby-identifier">post</span>.<span class="ruby-identifier">author</span>.<span class="ruby-identifier">name</span>
  <span class="ruby-identifier">puts</span> <span class="ruby-string">&quot;Last comment on: &quot;</span> <span class="ruby-operator">+</span> <span class="ruby-identifier">post</span>.<span class="ruby-identifier">comments</span>.<span class="ruby-identifier">first</span>.<span class="ruby-identifier">created_on</span>
<span class="ruby-keyword">end</span>
</pre>

<p>To iterate over these one hundred posts, we’ll generate 201 database
queries. Let’s first just optimize it for retrieving the author:</p>

<pre class="ruby"><span class="ruby-constant">Post</span>.<span class="ruby-identifier">includes</span>(:<span class="ruby-identifier">author</span>).<span class="ruby-identifier">each</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">post</span><span class="ruby-operator">|</span>
</pre>

<p>This references the name of the <code>belongs_to</code> association that
also used the <code>:author</code> symbol. After loading the posts, find
will collect the <code>author_id</code> from each one and load all the
referenced authors with one query. Doing so will cut down the number of
queries from 201 to 102.</p>

<p>We can improve upon the situation further by referencing both associations
in the finder with:</p>

<pre class="ruby"><span class="ruby-constant">Post</span>.<span class="ruby-identifier">includes</span>(:<span class="ruby-identifier">author</span>, :<span class="ruby-identifier">comments</span>).<span class="ruby-identifier">each</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">post</span><span class="ruby-operator">|</span>
</pre>

<p>This will load all comments with a single query. This reduces the total
number of queries to 3. More generally the number of queries will be 1 plus
the number of associations named (except if some of the associations are
polymorphic <code>belongs_to</code> - see below).</p>

<p>To include a deep hierarchy of associations, use a hash:</p>

<pre class="ruby"><span class="ruby-constant">Post</span>.<span class="ruby-identifier">includes</span>(:<span class="ruby-identifier">author</span>, {:<span class="ruby-identifier">comments</span> =<span class="ruby-operator">&gt;</span> {:<span class="ruby-identifier">author</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">gravatar</span>}}).<span class="ruby-identifier">each</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">post</span><span class="ruby-operator">|</span>
</pre>

<p>That’ll grab not only all the comments but all their authors and gravatar
pictures. You can mix and match symbols, arrays and hashes in any
combination to describe the associations you want to load.</p>

<p>All of this power shouldn’t fool you into thinking that you can pull out
huge amounts of data with no performance penalty just because you’ve
reduced the number of queries. The database still needs to send all the
data to Active Record and it still needs to be processed. So it’s no
catch-all for performance problems, but it’s a great way to cut down on the
number of queries in a situation as the one described above.</p>

<p>Since only one table is loaded at a time, conditions or orders cannot
reference tables other than the main one. If this is the case Active Record
falls back to the previously used LEFT OUTER JOIN based strategy. For
example</p>

<pre>Post.includes([:author, :comments]).where(['comments.approved = ?', true]).all</pre>

<p>This will result in a single SQL query with joins along the lines of:
<code>LEFT OUTER JOIN comments ON comments.post_id = posts.id</code> and
<code>LEFT OUTER JOIN authors ON authors.id = posts.author_id</code>. Note
that using conditions like this can have unintended consequences. In the
above example posts with no approved comments are not returned at all,
because the conditions apply to the SQL statement as a whole and not just
to the association. You must disambiguate column references for this
fallback to happen, for example <code>:order =&gt; &quot;author.name
DESC&quot;</code> will work but <code>:order =&gt; &quot;name
DESC&quot;</code> will not.</p>

<p>If you do want eager load only some members of an association it is usually
more natural to include an association which has conditions defined on it:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Post</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">approved_comments</span>, :<span class="ruby-identifier">class_name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">'Comment'</span>, :<span class="ruby-identifier">conditions</span> =<span class="ruby-operator">&gt;</span> [<span class="ruby-string">'approved = ?'</span>, <span class="ruby-keyword">true</span>]
<span class="ruby-keyword">end</span>

<span class="ruby-constant">Post</span>.<span class="ruby-identifier">includes</span>(:<span class="ruby-identifier">approved_comments</span>)
</pre>

<p>This will load posts and eager load the <code>approved_comments</code>
association, which contains only those comments that have been approved.</p>

<p>If you eager load an association with a specified <code>:limit</code>
option, it will be ignored, returning all the associated objects:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Picture</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">most_recent_comments</span>, :<span class="ruby-identifier">class_name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">'Comment'</span>, :<span class="ruby-identifier">order</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">'id DESC'</span>, :<span class="ruby-identifier">limit</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-value">10</span>
<span class="ruby-keyword">end</span>

<span class="ruby-constant">Picture</span>.<span class="ruby-identifier">includes</span>(:<span class="ruby-identifier">most_recent_comments</span>).<span class="ruby-identifier">first</span>.<span class="ruby-identifier">most_recent_comments</span> <span class="ruby-comment"># =&gt; returns all associated comments.</span>
</pre>

<p>When eager loaded, conditions are interpolated in the context of the model
class, not the model instance. Conditions are lazily interpolated before
the actual model exists.</p>

<p>Eager loading is supported with polymorphic associations.</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Address</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">addressable</span>, :<span class="ruby-identifier">polymorphic</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>
<span class="ruby-keyword">end</span>
</pre>

<p>A call that tries to eager load the addressable model</p>

<pre>Address.includes(:addressable)</pre>

<p>This will execute one query to load the addresses and load the addressables
with one query per addressable type. For example if all the addressables
are either of class Person or Company then a total of 3 queries will be
executed. The list of addressable types to load is determined on the back
of the addresses loaded. This is not supported if Active Record has to
fallback to the previous implementation of eager loading and will raise
ActiveRecord::EagerLoadPolymorphicError. The reason is that the parent
model’s type is a column value so its corresponding table name cannot be
put in the <code>FROM</code>/<code>JOIN</code> clauses of that query.</p>

<h2 id="label-Table+Aliasing">Table Aliasing</h2>

<p>Active Record uses table aliasing in the case that a table is referenced
multiple times in a join. If a table is referenced only once, the standard
table name is used. The second time, the table is aliased as
<code>#{reflection_name}_#{parent_table_name}</code>. Indexes are appended
for any more successive uses of the table name.</p>

<pre class="ruby"><span class="ruby-constant">Post</span>.<span class="ruby-identifier">joins</span>(:<span class="ruby-identifier">comments</span>)
<span class="ruby-comment"># =&gt; SELECT ... FROM posts INNER JOIN comments ON ...</span>
<span class="ruby-constant">Post</span>.<span class="ruby-identifier">joins</span>(:<span class="ruby-identifier">special_comments</span>) <span class="ruby-comment"># STI</span>
<span class="ruby-comment"># =&gt; SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'</span>
<span class="ruby-constant">Post</span>.<span class="ruby-identifier">joins</span>(:<span class="ruby-identifier">comments</span>, :<span class="ruby-identifier">special_comments</span>) <span class="ruby-comment"># special_comments is the reflection name, posts is the parent table name</span>
<span class="ruby-comment"># =&gt; SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts</span>
</pre>

<p>Acts as tree example:</p>

<pre class="ruby"><span class="ruby-constant">TreeMixin</span>.<span class="ruby-identifier">joins</span>(:<span class="ruby-identifier">children</span>)
<span class="ruby-comment"># =&gt; SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...</span>
<span class="ruby-constant">TreeMixin</span>.<span class="ruby-identifier">joins</span>(:<span class="ruby-identifier">children</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">parent</span>)
<span class="ruby-comment"># =&gt; SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...</span>
                            <span class="ruby-constant">INNER</span> <span class="ruby-constant">JOIN</span> <span class="ruby-identifier">parents_mixins</span> <span class="ruby-operator">...</span>
<span class="ruby-constant">TreeMixin</span>.<span class="ruby-identifier">joins</span>(:<span class="ruby-identifier">children</span> =<span class="ruby-operator">&gt;</span> {:<span class="ruby-identifier">parent</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">children</span>})
<span class="ruby-comment"># =&gt; SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...</span>
                            <span class="ruby-constant">INNER</span> <span class="ruby-constant">JOIN</span> <span class="ruby-identifier">parents_mixins</span> <span class="ruby-operator">...</span>
                            <span class="ruby-constant">INNER</span> <span class="ruby-constant">JOIN</span> <span class="ruby-identifier">mixins</span> <span class="ruby-identifier">childrens_mixins_2</span>
</pre>

<p>Has and Belongs to Many join tables use the same idea, but add a
<code>_join</code> suffix:</p>

<pre class="ruby"><span class="ruby-constant">Post</span>.<span class="ruby-identifier">joins</span>(:<span class="ruby-identifier">categories</span>)
<span class="ruby-comment"># =&gt; SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...</span>
<span class="ruby-constant">Post</span>.<span class="ruby-identifier">joins</span>(:<span class="ruby-identifier">categories</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">posts</span>)
<span class="ruby-comment"># =&gt; SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...</span>
                           <span class="ruby-constant">INNER</span> <span class="ruby-constant">JOIN</span> <span class="ruby-identifier">categories_posts</span> <span class="ruby-identifier">posts_categories_join</span> <span class="ruby-constant">INNER</span> <span class="ruby-constant">JOIN</span> <span class="ruby-identifier">posts</span> <span class="ruby-identifier">posts_categories</span>
<span class="ruby-constant">Post</span>.<span class="ruby-identifier">joins</span>(:<span class="ruby-identifier">categories</span> =<span class="ruby-operator">&gt;</span> {:<span class="ruby-identifier">posts</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">categories</span>})
<span class="ruby-comment"># =&gt; SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...</span>
                           <span class="ruby-constant">INNER</span> <span class="ruby-constant">JOIN</span> <span class="ruby-identifier">categories_posts</span> <span class="ruby-identifier">posts_categories_join</span> <span class="ruby-constant">INNER</span> <span class="ruby-constant">JOIN</span> <span class="ruby-identifier">posts</span> <span class="ruby-identifier">posts_categories</span>
                           <span class="ruby-constant">INNER</span> <span class="ruby-constant">JOIN</span> <span class="ruby-identifier">categories_posts</span> <span class="ruby-identifier">categories_posts_join</span> <span class="ruby-constant">INNER</span> <span class="ruby-constant">JOIN</span> <span class="ruby-identifier">categories</span> <span class="ruby-identifier">categories_posts_2</span>
</pre>

<p>If you wish to specify your own custom joins using <code>joins</code>
method, those table names will take precedence over the eager associations:</p>

<pre class="ruby"><span class="ruby-constant">Post</span>.<span class="ruby-identifier">joins</span>(:<span class="ruby-identifier">comments</span>).<span class="ruby-identifier">joins</span>(<span class="ruby-string">&quot;inner join comments ...&quot;</span>)
<span class="ruby-comment"># =&gt; SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...</span>
<span class="ruby-constant">Post</span>.<span class="ruby-identifier">joins</span>(:<span class="ruby-identifier">comments</span>, :<span class="ruby-identifier">special_comments</span>).<span class="ruby-identifier">joins</span>(<span class="ruby-string">&quot;inner join comments ...&quot;</span>)
<span class="ruby-comment"># =&gt; SELECT ... FROM posts INNER JOIN comments comments_posts ON ...</span>
                           <span class="ruby-constant">INNER</span> <span class="ruby-constant">JOIN</span> <span class="ruby-identifier">comments</span> <span class="ruby-identifier">special_comments_posts</span> <span class="ruby-operator">...</span>
                           <span class="ruby-constant">INNER</span> <span class="ruby-constant">JOIN</span> <span class="ruby-identifier">comments</span> <span class="ruby-operator">...</span>
</pre>

<p>Table aliases are automatically truncated according to the maximum length
of table identifiers according to the specific database.</p>

<h2 id="label-Modules">Modules</h2>

<p>By default, associations will look for objects within the current module
scope. Consider:</p>

<pre class="ruby"><span class="ruby-keyword">module</span> <span class="ruby-constant">MyApplication</span>
  <span class="ruby-keyword">module</span> <span class="ruby-constant">Business</span>
    <span class="ruby-keyword">class</span> <span class="ruby-constant">Firm</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
       <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">clients</span>
     <span class="ruby-keyword">end</span>

    <span class="ruby-keyword">class</span> <span class="ruby-constant">Client</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>; <span class="ruby-keyword">end</span>
  <span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
</pre>

<p>When <code>Firm#clients</code> is called, it will in turn call
<code>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</code>.
If you want to associate with a class in another module scope, this can be
done by specifying the complete class name.</p>

<pre class="ruby"><span class="ruby-keyword">module</span> <span class="ruby-constant">MyApplication</span>
  <span class="ruby-keyword">module</span> <span class="ruby-constant">Business</span>
    <span class="ruby-keyword">class</span> <span class="ruby-constant">Firm</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>; <span class="ruby-keyword">end</span>
  <span class="ruby-keyword">end</span>

  <span class="ruby-keyword">module</span> <span class="ruby-constant">Billing</span>
    <span class="ruby-keyword">class</span> <span class="ruby-constant">Account</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
      <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">firm</span>, :<span class="ruby-identifier">class_name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;MyApplication::Business::Firm&quot;</span>
    <span class="ruby-keyword">end</span>
  <span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
</pre>

<h2 id="label-Bi-directional+associations">Bi-directional associations</h2>

<p>When you specify an association there is usually an association on the
associated model that specifies the same relationship in reverse. For
example, with the following models:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Dungeon</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">traps</span>
  <span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">evil_wizard</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Trap</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">dungeon</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">EvilWizard</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">dungeon</span>
<span class="ruby-keyword">end</span>
</pre>

<p>The <code>traps</code> association on <code>Dungeon</code> and the
<code>dungeon</code> association on <code>Trap</code> are the inverse of
each other and the inverse of the <code>dungeon</code> association on
<code>EvilWizard</code> is the <code>evil_wizard</code> association on
<code>Dungeon</code> (and vice-versa). By default, Active Record doesn’t
know anything about these inverse relationships and so no object loading
optimization is possible. For example:</p>

<pre class="ruby"><span class="ruby-identifier">d</span> = <span class="ruby-constant">Dungeon</span>.<span class="ruby-identifier">first</span>
<span class="ruby-identifier">t</span> = <span class="ruby-identifier">d</span>.<span class="ruby-identifier">traps</span>.<span class="ruby-identifier">first</span>
<span class="ruby-identifier">d</span>.<span class="ruby-identifier">level</span> <span class="ruby-operator">==</span> <span class="ruby-identifier">t</span>.<span class="ruby-identifier">dungeon</span>.<span class="ruby-identifier">level</span> <span class="ruby-comment"># =&gt; true</span>
<span class="ruby-identifier">d</span>.<span class="ruby-identifier">level</span> = <span class="ruby-value">10</span>
<span class="ruby-identifier">d</span>.<span class="ruby-identifier">level</span> <span class="ruby-operator">==</span> <span class="ruby-identifier">t</span>.<span class="ruby-identifier">dungeon</span>.<span class="ruby-identifier">level</span> <span class="ruby-comment"># =&gt; false</span>
</pre>

<p>The <code>Dungeon</code> instances <code>d</code> and
<code>t.dungeon</code> in the above example refer to the same object data
from the database, but are actually different in-memory copies of that
data. Specifying the <code>:inverse_of</code> option on associations lets
you tell Active Record about inverse relationships and it will optimise
object loading. For example, if we changed our model definitions to:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Dungeon</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">traps</span>, :<span class="ruby-identifier">inverse_of</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">dungeon</span>
  <span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">evil_wizard</span>, :<span class="ruby-identifier">inverse_of</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">dungeon</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">Trap</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">dungeon</span>, :<span class="ruby-identifier">inverse_of</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">traps</span>
<span class="ruby-keyword">end</span>

<span class="ruby-keyword">class</span> <span class="ruby-constant">EvilWizard</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Base</span>
  <span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">dungeon</span>, :<span class="ruby-identifier">inverse_of</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">evil_wizard</span>
<span class="ruby-keyword">end</span>
</pre>

<p>Then, from our code snippet above, <code>d</code> and
<code>t.dungeon</code> are actually the same in-memory instance and our
final <code>d.level == t.dungeon.level</code> will return
<code>true</code>.</p>

<p>There are limitations to <code>:inverse_of</code> support:</p>
<ul><li>
<p>does not work with <code>:through</code> associations.</p>
</li><li>
<p>does not work with <code>:polymorphic</code> associations.</p>
</li><li>
<p>for <code>belongs_to</code> associations <code>has_many</code> inverse
associations are ignored.</p>
</li></ul>

<h2 id="label-Deleting+from+associations">Deleting from associations</h2>

<h3 id="label-Dependent+associations">Dependent associations</h3>

<p><code>has_many</code>, <code>has_one</code> and <code>belongs_to</code>
associations support the <code>:dependent</code> option. This allows you to
specify that associated records should be deleted when the owner is
deleted.</p>

<p>For example:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">Author</span>
  <span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">posts</span>, :<span class="ruby-identifier">dependent</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">destroy</span>
<span class="ruby-keyword">end</span>
<span class="ruby-constant">Author</span>.<span class="ruby-identifier">find</span>(<span class="ruby-value">1</span>).<span class="ruby-identifier">destroy</span> <span class="ruby-comment"># =&gt; Will destroy all of the author's posts, too</span>
</pre>

<p>The <code>:dependent</code> option can have different values which specify
how the deletion is done. For more information, see the documentation for
this option on the different specific association types.</p>

<h3 id="label-Delete+or+destroy%3F">Delete or destroy?</h3>

<p><code>has_many</code> and <code>has_and_belongs_to_many</code> associations
have the methods <code>destroy</code>, <code>delete</code>,
<code>destroy_all</code> and <code>delete_all</code>.</p>

<p>For <code>has_and_belongs_to_many</code>, <code>delete</code> and
<code>destroy</code> are the same: they cause the records in the join table
to be removed.</p>

<p>For <code>has_many</code>, <code>destroy</code> will always call the
<code>destroy</code> method of the record(s) being removed so that
callbacks are run. However <code>delete</code> will either do the deletion
according to the strategy specified by the <code>:dependent</code> option,
or if no <code>:dependent</code> option is given, then it will follow the
default strategy. The default strategy is <code>:nullify</code> (set the
foreign keys to <code>nil</code>), except for <code>has_many</code>
<code>:through</code>, where the default strategy is
<code>delete_all</code> (delete the join records, without running their
callbacks).</p>

<p>There is also a <code>clear</code> method which is the same as
<code>delete_all</code>, except that it returns the association rather than
the records which have been deleted.</p>

<h3 id="label-What+gets+deleted%3F">What gets deleted?</h3>

<p>There is a potential pitfall here: <code>has_and_belongs_to_many</code> and
<code>has_many</code> <code>:through</code> associations have records in
join tables, as well as the associated records. So when we call one of
these deletion methods, what exactly should be deleted?</p>

<p>The answer is that it is assumed that deletion on an association is about
removing the <em>link</em> between the owner and the associated object(s),
rather than necessarily the associated objects themselves. So with
<code>has_and_belongs_to_many</code> and <code>has_many</code>
<code>:through</code>, the join records will be deleted, but the associated
records won’t.</p>

<p>This makes sense if you think about it: if you were to call
<code>post.tags.delete(Tag.find_by_name('food'))</code> you would want the
‘food’ tag to be unlinked from the post, rather than for the tag itself to
be removed from the database.</p>

<p>However, there are examples where this strategy doesn’t make sense. For
example, suppose a person has many projects, and each project has many
tasks. If we deleted one of a person’s tasks, we would probably not want
the project to be deleted. In this scenario, the delete method won’t
actually work: it can only be used if the association on the join model is
a <code>belongs_to</code>. In other situations you are expected to perform
operations directly on either the associated records or the
<code>:through</code> association.</p>

<p>With a regular <code>has_many</code> there is no distinction between the
“associated records” and the “link”, so there is only one choice for what
gets deleted.</p>

<p>With <code>has_and_belongs_to_many</code> and <code>has_many</code>
<code>:through</code>, if you want to delete the associated records
themselves, you can always do something along the lines of
<code>person.tasks.each(&amp;:destroy)</code>.</p>

<h2 id="label-Type+safety+with+ActiveRecord%3A%3AAssociationTypeMismatch">Type safety with <code>ActiveRecord::AssociationTypeMismatch</code></h2>

<p>If you attempt to assign an object to an association that doesn’t match the
inferred or specified <code>:class_name</code>, you’ll get an
<code>ActiveRecord::AssociationTypeMismatch</code>.</p>

<h2 id="label-Options">Options</h2>

<p>All of the association macros can be specialized through options. This
makes cases more complex than the simple and guessable ones possible.</p>

  </div><!-- description -->

  
  
  
  <section id="5Buntitled-5D" class="documentation-section">
    

    

    

    

    <!-- Methods -->
    
     <section id="public-instance-5Buntitled-5D-method-details" class="method-section section">
      <h3 class="section-header">Public Instance Methods</h3>

    
      <div id="method-i-belongs_to" class="method-detail ">
        
        <div class="method-heading">
          <span class="method-name">belongs_to</span><span
            class="method-args">(name, options = {})</span>
          <span class="method-click-advice">click to toggle source</span>
        </div>
        

        <div class="method-description">
          
          <p>Specifies a one-to-one association with another class. This method should
only be used if this class contains the foreign key. If the other class
contains the foreign key, then you should use <code>has_one</code> instead.
See also ActiveRecord::Associations::ClassMethods’s overview on when to use
<code>has_one</code> and when to use <code>belongs_to</code>.</p>

<p>Methods will be added for retrieval and query for a single associated
object, for which this object holds an id:</p>
<dl class="rdoc-list label-list"><dt>association(force_reload = false)
<dd>
<p>Returns the associated object. <code>nil</code> is returned if none is
found.</p>
</dd><dt>association=(associate)
<dd>
<p>Assigns the associate object, extracts the primary key, and sets it as the
foreign key.</p>
</dd><dt>build_association(attributes = {})
<dd>
<p>Returns a new object of the associated type that has been instantiated with
<code>attributes</code> and linked to this object through a foreign key,
but has not yet been saved.</p>
</dd><dt>create_association(attributes = {})
<dd>
<p>Returns a new object of the associated type that has been instantiated with
<code>attributes</code>, linked to this object through a foreign key, and
that has already been saved (if it passed the validation).</p>
</dd><dt>create_association!(attributes = {})
<dd>
<p>Does the same as <code>create_association</code>, but raises
<code>ActiveRecord::RecordInvalid</code> if the record is invalid.</p>
</dd></dl>

<p>(<code>association</code> is replaced with the symbol passed as the first
argument, so <code>belongs_to :author</code> would add among others
<code>author.nil?</code>.)</p>

<h3 id="method-i-belongs_to-label-Example">Example</h3>

<p>A Post class declares <code>belongs_to :author</code>, which will add:</p>
<ul><li>
<p><code>Post#author</code> (similar to <code>Author.find(author_id)</code>)</p>
</li><li>
<p><code>Post#author=(author)</code> (similar to <code>post.author_id =
author.id</code>)</p>
</li><li>
<p><code>Post#build_author</code> (similar to <code>post.author =
Author.new</code>)</p>
</li><li>
<p><code>Post#create_author</code> (similar to <code>post.author = Author.new;
post.author.save; post.author</code>)</p>
</li><li>
<p><code>Post#create_author!</code> (similar to <code>post.author =
Author.new; post.author.save!; post.author</code>)</p>
</li></ul>

<p>The declaration can also include an options hash to specialize the behavior
of the association.</p>

<h3 id="method-i-belongs_to-label-Options">Options</h3>
<dl class="rdoc-list label-list"><dt>:class_name
<dd>
<p>Specify the class name of the association. Use it only if that name can’t
be inferred from the association name. So <code>belongs_to :author</code>
will by default be linked to the Author class, but if the real class name
is Person, you’ll have to specify it with this option.</p>
</dd><dt>:conditions
<dd>
<p>Specify the conditions that the associated object must meet in order to be
included as a <code>WHERE</code> SQL fragment, such as <code>authorized =
1</code>.</p>
</dd><dt>:select
<dd>
<p>By default, this is <code>*</code> as in <code>SELECT * FROM</code>, but
can be changed if, for example, you want to do a join but not include the
joined columns. Do not forget to include the primary and foreign keys,
otherwise it will raise an error.</p>
</dd><dt>:foreign_key
<dd>
<p>Specify the foreign key used for the association. By default this is
guessed to be the name of the association with an “_id” suffix. So a class
that defines a <code>belongs_to :person</code> association will use
“person_id” as the default <code>:foreign_key</code>. Similarly,
<code>belongs_to :favorite_person, :class_name =&gt;
&quot;Person&quot;</code> will use a foreign key of “favorite_person_id”.</p>
</dd><dt>:foreign_type
<dd>
<p>Specify the column used to store the associated object’s type, if this is a
polymorphic association. By default this is guessed to be the name of the
association with a “_type” suffix. So a class that defines a
<code>belongs_to :taggable, :polymorphic =&gt; true</code> association will
use “taggable_type” as the default <code>:foreign_type</code>.</p>
</dd><dt>:primary_key
<dd>
<p>Specify the method that returns the primary key of associated object used
for the association. By default this is id.</p>
</dd><dt>:dependent
<dd>
<p>If set to <code>:destroy</code>, the associated object is destroyed when
this object is. If set to <code>:delete</code>, the associated object is
deleted <strong>without</strong> calling its destroy method. This option
should not be specified when <code>belongs_to</code> is used in conjunction
with a <code>has_many</code> relationship on another class because of the
potential to leave orphaned records behind.</p>
</dd><dt>:counter_cache
<dd>
<p>Caches the number of belonging objects on the associate class through the
use of <code>increment_counter</code> and <code>decrement_counter</code>.
The counter cache is incremented when an object of this class is created
and decremented when it’s destroyed. This requires that a column named
<code>#{table_name}_count</code> (such as <code>comments_count</code> for a
belonging Comment class) is used on the associate class (such as a Post
class). You can also specify a custom counter cache column by providing a
column name instead of a <code>true</code>/<code>false</code> value to this
option (e.g., <code>:counter_cache =&gt; :my_custom_counter</code>.) Note:
Specifying a counter cache will add it to that model’s list of readonly
attributes using <code>attr_readonly</code>.</p>
</dd><dt>:include
<dd>
<p>Specify second-order associations that should be eager loaded when this
object is loaded.</p>
</dd><dt>:polymorphic
<dd>
<p>Specify this association is a polymorphic association by passing
<code>true</code>. Note: If you’ve enabled the counter cache, then you may
want to add the counter cache attribute to the <code>attr_readonly</code>
list in the associated classes (e.g. <code>class Post; attr_readonly
:comments_count; end</code>).</p>
</dd><dt>:readonly
<dd>
<p>If true, the associated object is readonly through the association.</p>
</dd><dt>:validate
<dd>
<p>If <code>false</code>, don’t validate the associated objects when saving
the parent object. <code>false</code> by default.</p>
</dd><dt>:autosave
<dd>
<p>If true, always save the associated object or destroy it if marked for
destruction, when saving the parent object. If false, never save or destroy
the associated object. By default, only save the associated object if it’s
a new record.</p>
</dd><dt>:touch
<dd>
<p>If true, the associated object will be touched (the updated_at/on
attributes set to now) when this record is either saved or destroyed. If
you specify a symbol, that attribute will be updated with the current time
in addition to the updated_at/on attribute.</p>
</dd><dt>:inverse_of
<dd>
<p>Specifies the name of the <code>has_one</code> or <code>has_many</code>
association on the associated object that is the inverse of this
<code>belongs_to</code> association. Does not work in combination with the
<code>:polymorphic</code> options. See
ActiveRecord::Associations::ClassMethods’s overview on Bi-directional
associations for more detail.</p>
</dd></dl>

<p>Option examples:</p>

<pre class="ruby"><span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">firm</span>, :<span class="ruby-identifier">foreign_key</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;client_of&quot;</span>
<span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">person</span>, :<span class="ruby-identifier">primary_key</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;name&quot;</span>, :<span class="ruby-identifier">foreign_key</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;person_name&quot;</span>
<span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">author</span>, :<span class="ruby-identifier">class_name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;Person&quot;</span>, :<span class="ruby-identifier">foreign_key</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;author_id&quot;</span>
<span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">valid_coupon</span>, :<span class="ruby-identifier">class_name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;Coupon&quot;</span>, :<span class="ruby-identifier">foreign_key</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;coupon_id&quot;</span>,
           :<span class="ruby-identifier">conditions</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">'discounts &gt; #{payments_count}'</span>
<span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">attachable</span>, :<span class="ruby-identifier">polymorphic</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>
<span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">project</span>, :<span class="ruby-identifier">readonly</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>
<span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">post</span>, :<span class="ruby-identifier">counter_cache</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>
<span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">company</span>, :<span class="ruby-identifier">touch</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>
<span class="ruby-identifier">belongs_to</span> :<span class="ruby-identifier">company</span>, :<span class="ruby-identifier">touch</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">employees_last_updated_at</span>
</pre>
          

          
          <div class="method-source-code" id="belongs_to-source">
            <pre><span class="ruby-comment"># File /usr/local/lib/ruby/gems/1.9.1/gems/activerecord-3.2.7/lib/active_record/associations.rb, line 1427</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">belongs_to</span>(<span class="ruby-identifier">name</span>, <span class="ruby-identifier">options</span> = {})
  <span class="ruby-constant">Builder</span><span class="ruby-operator">::</span><span class="ruby-constant">BelongsTo</span>.<span class="ruby-identifier">build</span>(<span class="ruby-keyword">self</span>, <span class="ruby-identifier">name</span>, <span class="ruby-identifier">options</span>)
<span class="ruby-keyword">end</span></pre>
          </div><!-- belongs_to-source -->
          
        </div>

        

        
      </div><!-- belongs_to-method -->

    
      <div id="method-i-has_and_belongs_to_many" class="method-detail ">
        
        <div class="method-heading">
          <span class="method-name">has_and_belongs_to_many</span><span
            class="method-args">(name, options = {}, &extension)</span>
          <span class="method-click-advice">click to toggle source</span>
        </div>
        

        <div class="method-description">
          
          <p>Specifies a many-to-many relationship with another class. This associates
two classes via an intermediate join table. Unless the join table is
explicitly specified as an option, it is guessed using the lexical order of
the class names. So a join between Developer and Project will give the
default join table name of “developers_projects” because “D” outranks “P”.
Note that this precedence is calculated using the <code>&lt;</code>
operator for <a href="../../String.html">String</a>. This means that if the
strings are of different lengths, and the strings are equal when compared
up to the shortest length, then the longer string is considered of higher
lexical precedence than the shorter one. For example, one would expect the
tables “paper_boxes” and “papers” to generate a join table name of
“papers_paper_boxes” because of the length of the name “paper_boxes”, but
it in fact generates a join table name of “paper_boxes_papers”. Be aware of
this caveat, and use the custom <code>:join_table</code> option if you need
to.</p>

<p>The join table should not have a primary key or a model associated with it.
You must manually generate the join table with a migration such as this:</p>

<pre class="ruby"><span class="ruby-keyword">class</span> <span class="ruby-constant">CreateDevelopersProjectsJoinTable</span> <span class="ruby-operator">&lt;</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Migration</span>
  <span class="ruby-keyword">def</span> <span class="ruby-identifier">change</span>
    <span class="ruby-identifier">create_table</span> :<span class="ruby-identifier">developers_projects</span>, :<span class="ruby-identifier">id</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">false</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">t</span><span class="ruby-operator">|</span>
      <span class="ruby-identifier">t</span>.<span class="ruby-identifier">integer</span> :<span class="ruby-identifier">developer_id</span>
      <span class="ruby-identifier">t</span>.<span class="ruby-identifier">integer</span> :<span class="ruby-identifier">project_id</span>
    <span class="ruby-keyword">end</span>
  <span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
</pre>

<p>It’s also a good idea to add indexes to each of those columns to speed up
the joins process. However, in MySQL it is advised to add a compound index
for both of the columns as MySQL only uses one index per table during the
lookup.</p>

<p>Adds the following methods for retrieval and query:</p>
<dl class="rdoc-list label-list"><dt>collection(force_reload = false)
<dd>
<p>Returns an array of all the associated objects. An empty array is returned
if none are found.</p>
</dd><dt>collection&lt;&lt;(object, …)
<dd>
<p>Adds one or more objects to the collection by creating associations in the
join table (<code>collection.push</code> and <code>collection.concat</code>
are aliases to this method). Note that this operation instantly fires
update sql without waiting for the save or update call on the parent
object.</p>
</dd><dt>collection.delete(object, …)
<dd>
<p>Removes one or more objects from the collection by removing their
associations from the join table. This does not destroy the objects.</p>
</dd><dt>collection=objects
<dd>
<p>Replaces the collection’s content by deleting and adding objects as
appropriate.</p>
</dd><dt>collection_singular_ids
<dd>
<p>Returns an array of the associated objects’ ids.</p>
</dd><dt>collection_singular_ids=ids
<dd>
<p>Replace the collection by the objects identified by the primary keys in
<code>ids</code>.</p>
</dd><dt>collection.clear
<dd>
<p>Removes every object from the collection. This does not destroy the
objects.</p>
</dd><dt>collection.empty?
<dd>
<p>Returns <code>true</code> if there are no associated objects.</p>
</dd><dt>collection.size
<dd>
<p>Returns the number of associated objects.</p>
</dd><dt>collection.find(id)
<dd>
<p>Finds an associated object responding to the <code>id</code> and that meets
the condition that it has to be associated with this object. Uses the same
rules as ActiveRecord::Base.find.</p>
</dd><dt>collection.exists?(…)
<dd>
<p>Checks whether an associated object with the given conditions exists. Uses
the same rules as ActiveRecord::Base.exists?.</p>
</dd><dt>collection.build(attributes = {})
<dd>
<p>Returns a new object of the collection type that has been instantiated with
<code>attributes</code> and linked to this object through the join table,
but has not yet been saved.</p>
</dd><dt>collection.create(attributes = {})
<dd>
<p>Returns a new object of the collection type that has been instantiated with
<code>attributes</code>, linked to this object through the join table, and
that has already been saved (if it passed the validation).</p>
</dd></dl>

<p>(<code>collection</code> is replaced with the symbol passed as the first
argument, so <code>has_and_belongs_to_many :categories</code> would add
among others <code>categories.empty?</code>.)</p>

<h3 id="method-i-has_and_belongs_to_many-label-Example">Example</h3>

<p>A Developer class declares <code>has_and_belongs_to_many :projects</code>,
which will add:</p>
<ul><li>
<p><code>Developer#projects</code></p>
</li><li>
<p><code>Developer#projects&lt;&lt;</code></p>
</li><li>
<p><code>Developer#projects.delete</code></p>
</li><li>
<p><code>Developer#projects=</code></p>
</li><li>
<p><code>Developer#project_ids</code></p>
</li><li>
<p><code>Developer#project_ids=</code></p>
</li><li>
<p><code>Developer#projects.clear</code></p>
</li><li>
<p><code>Developer#projects.empty?</code></p>
</li><li>
<p><code>Developer#projects.size</code></p>
</li><li>
<p><code>Developer#projects.find(id)</code></p>
</li><li>
<p><code>Developer#projects.exists?(...)</code></p>
</li><li>
<p><code>Developer#projects.build</code> (similar to
<code>Project.new(&quot;developer_id&quot; =&gt; id)</code>)</p>
</li><li>
<p><code>Developer#projects.create</code> (similar to <code>c =
Project.new(&quot;developer_id&quot; =&gt; id); c.save; c</code>)</p>
</li></ul>

<p>The declaration may include an options hash to specialize the behavior of
the association.</p>

<h3 id="method-i-has_and_belongs_to_many-label-Options">Options</h3>
<dl class="rdoc-list label-list"><dt>:class_name
<dd>
<p>Specify the class name of the association. Use it only if that name can’t
be inferred from the association name. So <code>has_and_belongs_to_many
:projects</code> will by default be linked to the Project class, but if the
real class name is SuperProject, you’ll have to specify it with this
option.</p>
</dd><dt>:join_table
<dd>
<p>Specify the name of the join table if the default based on lexical order
isn’t what you want. <strong>WARNING:</strong> If you’re overwriting the
table name of either class, the <code>table_name</code> method MUST be
declared underneath any <code>has_and_belongs_to_many</code> declaration in
order to work.</p>
</dd><dt>:foreign_key
<dd>
<p>Specify the foreign key used for the association. By default this is
guessed to be the name of this class in lower-case and “_id” suffixed. So a
Person class that makes a <code>has_and_belongs_to_many</code> association
to Project will use “person_id” as the default <code>:foreign_key</code>.</p>
</dd><dt>:association_foreign_key
<dd>
<p>Specify the foreign key used for the association on the receiving side of
the association. By default this is guessed to be the name of the
associated class in lower-case and “_id” suffixed. So if a Person class
makes a <code>has_and_belongs_to_many</code> association to Project, the
association will use “project_id” as the default
<code>:association_foreign_key</code>.</p>
</dd><dt>:conditions
<dd>
<p>Specify the conditions that the associated object must meet in order to be
included as a <code>WHERE</code> SQL fragment, such as <code>authorized =
1</code>. Record creations from the association are scoped if a hash is
used. <code>has_many :posts, :conditions =&gt; {:published =&gt;
true}</code> will create published posts with
<code>@blog.posts.create</code> or <code>@blog.posts.build</code>.</p>
</dd><dt>:order
<dd>
<p>Specify the order in which the associated objects are returned as an
<code>ORDER BY</code> SQL fragment, such as <code>last_name, first_name
DESC</code></p>
</dd><dt>:uniq
<dd>
<p>If true, duplicate associated objects will be ignored by accessors and
query methods.</p>
</dd><dt>:finder_sql
<dd>
<p>Overwrite the default generated SQL statement used to fetch the association
with a manual statement</p>
</dd><dt>:counter_sql
<dd>
<p>Specify a complete SQL statement to fetch the size of the association. If
<code>:finder_sql</code> is specified but not <code>:counter_sql</code>,
<code>:counter_sql</code> will be generated by replacing <code>SELECT ...
FROM</code> with <code>SELECT COUNT(*) FROM</code>.</p>
</dd><dt>:delete_sql
<dd>
<p>Overwrite the default generated SQL statement used to remove links between
the associated classes with a manual statement.</p>
</dd><dt>:insert_sql
<dd>
<p>Overwrite the default generated SQL statement used to add links between the
associated classes with a manual statement.</p>
</dd><dt>:extend
<dd>
<p>Anonymous module for extending the proxy, see “Association extensions”.</p>
</dd><dt>:include
<dd>
<p>Specify second-order associations that should be eager loaded when the
collection is loaded.</p>
</dd><dt>:group
<dd>
<p>An attribute name by which the result should be grouped. Uses the
<code>GROUP BY</code> SQL-clause.</p>
</dd><dt>:having
<dd>
<p>Combined with <code>:group</code> this can be used to filter the records
that a <code>GROUP BY</code> returns. Uses the <code>HAVING</code>
SQL-clause.</p>
</dd><dt>:limit
<dd>
<p>An integer determining the limit on the number of rows that should be
returned.</p>
</dd><dt>:offset
<dd>
<p>An integer determining the offset from where the rows should be fetched. So
at 5, it would skip the first 4 rows.</p>
</dd><dt>:select
<dd>
<p>By default, this is <code>*</code> as in <code>SELECT * FROM</code>, but
can be changed if, for example, you want to do a join but not include the
joined columns. Do not forget to include the primary and foreign keys,
otherwise it will raise an error.</p>
</dd><dt>:readonly
<dd>
<p>If true, all the associated objects are readonly through the association.</p>
</dd><dt>:validate
<dd>
<p>If <code>false</code>, don’t validate the associated objects when saving
the parent object. <code>true</code> by default.</p>
</dd><dt>:autosave
<dd>
<p>If true, always save the associated objects or destroy them if marked for
destruction, when saving the parent object. If false, never save or destroy
the associated objects. By default, only save associated objects that are
new records.</p>
</dd></dl>

<p>Option examples:</p>

<pre class="ruby"><span class="ruby-identifier">has_and_belongs_to_many</span> :<span class="ruby-identifier">projects</span>
<span class="ruby-identifier">has_and_belongs_to_many</span> :<span class="ruby-identifier">projects</span>, :<span class="ruby-identifier">include</span> =<span class="ruby-operator">&gt;</span> [ :<span class="ruby-identifier">milestones</span>, :<span class="ruby-identifier">manager</span> ]
<span class="ruby-identifier">has_and_belongs_to_many</span> :<span class="ruby-identifier">nations</span>, :<span class="ruby-identifier">class_name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;Country&quot;</span>
<span class="ruby-identifier">has_and_belongs_to_many</span> :<span class="ruby-identifier">categories</span>, :<span class="ruby-identifier">join_table</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;prods_cats&quot;</span>
<span class="ruby-identifier">has_and_belongs_to_many</span> :<span class="ruby-identifier">categories</span>, :<span class="ruby-identifier">readonly</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>
<span class="ruby-identifier">has_and_belongs_to_many</span> :<span class="ruby-identifier">active_projects</span>, :<span class="ruby-identifier">join_table</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">'developers_projects'</span>, :<span class="ruby-identifier">delete_sql</span> =<span class="ruby-operator">&gt;</span>
<span class="ruby-node">&quot;DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}&quot;</span>
</pre>
          

          
          <div class="method-source-code" id="has_and_belongs_to_many-source">
            <pre><span class="ruby-comment"># File /usr/local/lib/ruby/gems/1.9.1/gems/activerecord-3.2.7/lib/active_record/associations.rb, line 1599</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">has_and_belongs_to_many</span>(<span class="ruby-identifier">name</span>, <span class="ruby-identifier">options</span> = {}, &amp;<span class="ruby-identifier">extension</span>)
  <span class="ruby-constant">Builder</span><span class="ruby-operator">::</span><span class="ruby-constant">HasAndBelongsToMany</span>.<span class="ruby-identifier">build</span>(<span class="ruby-keyword">self</span>, <span class="ruby-identifier">name</span>, <span class="ruby-identifier">options</span>, &amp;<span class="ruby-identifier">extension</span>)
<span class="ruby-keyword">end</span></pre>
          </div><!-- has_and_belongs_to_many-source -->
          
        </div>

        

        
      </div><!-- has_and_belongs_to_many-method -->

    
      <div id="method-i-has_many" class="method-detail ">
        
        <div class="method-heading">
          <span class="method-name">has_many</span><span
            class="method-args">(name, options = {}, &extension)</span>
          <span class="method-click-advice">click to toggle source</span>
        </div>
        

        <div class="method-description">
          
          <p>Specifies a one-to-many association. The following methods for retrieval
and query of collections of associated objects will be added:</p>
<dl class="rdoc-list label-list"><dt>collection(force_reload = false)
<dd>
<p>Returns an array of all the associated objects. An empty array is returned
if none are found.</p>
</dd><dt>collection&lt;&lt;(object, …)
<dd>
<p>Adds one or more objects to the collection by setting their foreign keys to
the collection’s primary key. Note that this operation instantly fires
update sql without waiting for the save or update call on the parent
object.</p>
</dd><dt>collection.delete(object, …)
<dd>
<p>Removes one or more objects from the collection by setting their foreign
keys to <code>NULL</code>. Objects will be in addition destroyed if they’re
associated with <code>:dependent =&gt; :destroy</code>, and deleted if
they’re associated with <code>:dependent =&gt; :delete_all</code>.</p>

<p>If the <code>:through</code> option is used, then the join records are
deleted (rather than nullified) by default, but you can specify
<code>:dependent =&gt; :destroy</code> or <code>:dependent =&gt;
:nullify</code> to override this.</p>
</dd><dt>collection=objects
<dd>
<p>Replaces the collections content by deleting and adding objects as
appropriate. If the <code>:through</code> option is true callbacks in the
join models are triggered except destroy callbacks, since deletion is
direct.</p>
</dd><dt>collection_singular_ids
<dd>
<p>Returns an array of the associated objects’ ids</p>
</dd><dt>collection_singular_ids=ids
<dd>
<p>Replace the collection with the objects identified by the primary keys in
<code>ids</code>. This method loads the models and calls
<code>collection=</code>. See above.</p>
</dd><dt>collection.clear
<dd>
<p>Removes every object from the collection. This destroys the associated
objects if they are associated with <code>:dependent =&gt; :destroy</code>,
deletes them directly from the database if <code>:dependent =&gt;
:delete_all</code>, otherwise sets their foreign keys to <code>NULL</code>.
If the <code>:through</code> option is true no destroy callbacks are
invoked on the join models. Join models are directly deleted.</p>
</dd><dt>collection.empty?
<dd>
<p>Returns <code>true</code> if there are no associated objects.</p>
</dd><dt>collection.size
<dd>
<p>Returns the number of associated objects.</p>
</dd><dt>collection.find(…)
<dd>
<p>Finds an associated object according to the same rules as
ActiveRecord::Base.find.</p>
</dd><dt>collection.exists?(…)
<dd>
<p>Checks whether an associated object with the given conditions exists. Uses
the same rules as ActiveRecord::Base.exists?.</p>
</dd><dt>collection.build(attributes = {}, …)
<dd>
<p>Returns one or more new objects of the collection type that have been
instantiated with <code>attributes</code> and linked to this object through
a foreign key, but have not yet been saved.</p>
</dd><dt>collection.create(attributes = {})
<dd>
<p>Returns a new object of the collection type that has been instantiated with
<code>attributes</code>, linked to this object through a foreign key, and
that has already been saved (if it passed the validation).
<strong>Note</strong>: This only works if the base model already exists in
the DB, not if it is a new (unsaved) record!</p>
</dd></dl>

<p>(<strong>Note</strong>: <code>collection</code> is replaced with the symbol
passed as the first argument, so <code>has_many :clients</code> would add
among others <code>clients.empty?</code>.)</p>

<h3 id="method-i-has_many-label-Example">Example</h3>

<p>Example: A Firm class declares <code>has_many :clients</code>, which will
add:</p>
<ul><li>
<p><code>Firm#clients</code> (similar to <code>Clients.all :conditions =&gt;
[&quot;firm_id = ?&quot;, id]</code>)</p>
</li><li>
<p><code>Firm#clients&lt;&lt;</code></p>
</li><li>
<p><code>Firm#clients.delete</code></p>
</li><li>
<p><code>Firm#clients=</code></p>
</li><li>
<p><code>Firm#client_ids</code></p>
</li><li>
<p><code>Firm#client_ids=</code></p>
</li><li>
<p><code>Firm#clients.clear</code></p>
</li><li>
<p><code>Firm#clients.empty?</code> (similar to <code>firm.clients.size ==
0</code>)</p>
</li><li>
<p><code>Firm#clients.size</code> (similar to <code>Client.count &quot;firm_id
= #{id}&quot;</code>)</p>
</li><li>
<p><code>Firm#clients.find</code> (similar to <code>Client.find(id,
:conditions =&gt; &quot;firm_id = #{id}&quot;)</code>)</p>
</li><li>
<p><code>Firm#clients.exists?(:name =&gt; 'ACME')</code> (similar to
<code>Client.exists?(:name =&gt; 'ACME', :firm_id =&gt; firm.id)</code>)</p>
</li><li>
<p><code>Firm#clients.build</code> (similar to
<code>Client.new(&quot;firm_id&quot; =&gt; id)</code>)</p>
</li><li>
<p><code>Firm#clients.create</code> (similar to <code>c =
Client.new(&quot;firm_id&quot; =&gt; id); c.save; c</code>)</p>
</li></ul>

<p>The declaration can also include an options hash to specialize the behavior
of the association.</p>

<h3 id="method-i-has_many-label-Options">Options</h3>
<dl class="rdoc-list label-list"><dt>:class_name
<dd>
<p>Specify the class name of the association. Use it only if that name can’t
be inferred from the association name. So <code>has_many :products</code>
will by default be linked to the Product class, but if the real class name
is SpecialProduct, you’ll have to specify it with this option.</p>
</dd><dt>:conditions
<dd>
<p>Specify the conditions that the associated objects must meet in order to be
included as a <code>WHERE</code> SQL fragment, such as <code>price &gt; 5
AND name LIKE 'B%'</code>. Record creations from the association are scoped
if a hash is used. <code>has_many :posts, :conditions =&gt; {:published
=&gt; true}</code> will create published posts with
<code>@blog.posts.create</code> or <code>@blog.posts.build</code>.</p>
</dd><dt>:order
<dd>
<p>Specify the order in which the associated objects are returned as an
<code>ORDER BY</code> SQL fragment, such as <code>last_name, first_name
DESC</code>.</p>
</dd><dt>:foreign_key
<dd>
<p>Specify the foreign key used for the association. By default this is
guessed to be the name of this class in lower-case and “_id” suffixed. So a
Person class that makes a <code>has_many</code> association will use
“person_id” as the default <code>:foreign_key</code>.</p>
</dd><dt>:primary_key
<dd>
<p>Specify the method that returns the primary key used for the association.
By default this is <code>id</code>.</p>
</dd><dt>:dependent
<dd>
<p>If set to <code>:destroy</code> all the associated objects are destroyed
alongside this object by calling their <code>destroy</code> method. If set
to <code>:delete_all</code> all associated objects are deleted
<strong>without</strong> calling their <code>destroy</code> method. If set
to <code>:nullify</code> all associated objects’ foreign keys are set to
<code>NULL</code> <strong>without</strong> calling their <code>save</code>
callbacks. If set to <code>:restrict</code> this object raises an
<code>ActiveRecord::DeleteRestrictionError</code> exception and cannot be
deleted if it has any associated objects.</p>

<p>If using with the <code>:through</code> option, the association on the join
model must be a <code>belongs_to</code>, and the records which get deleted
are the join records, rather than the associated records.</p>
</dd><dt>:finder_sql
<dd>
<p>Specify a complete SQL statement to fetch the association. This is a good
way to go for complex associations that depend on multiple tables. May be
supplied as a string or a proc where interpolation is required. Note: When
this option is used, <code>find_in_collection</code> is <em>not</em> added.</p>
</dd><dt>:counter_sql
<dd>
<p>Specify a complete SQL statement to fetch the size of the association. If
<code>:finder_sql</code> is specified but not <code>:counter_sql</code>,
<code>:counter_sql</code> will be generated by replacing <code>SELECT ...
FROM</code> with <code>SELECT COUNT(*) FROM</code>.</p>
</dd><dt>:extend
<dd>
<p>Specify a named module for extending the proxy. See “Association
extensions”.</p>
</dd><dt>:include
<dd>
<p>Specify second-order associations that should be eager loaded when the
collection is loaded.</p>
</dd><dt>:group
<dd>
<p>An attribute name by which the result should be grouped. Uses the
<code>GROUP BY</code> SQL-clause.</p>
</dd><dt>:having
<dd>
<p>Combined with <code>:group</code> this can be used to filter the records
that a <code>GROUP BY</code> returns. Uses the <code>HAVING</code>
SQL-clause.</p>
</dd><dt>:limit
<dd>
<p>An integer determining the limit on the number of rows that should be
returned.</p>
</dd><dt>:offset
<dd>
<p>An integer determining the offset from where the rows should be fetched. So
at 5, it would skip the first 4 rows.</p>
</dd><dt>:select
<dd>
<p>By default, this is <code>*</code> as in <code>SELECT * FROM</code>, but
can be changed if you, for example, want to do a join but not include the
joined columns. Do not forget to include the primary and foreign keys,
otherwise it will raise an error.</p>
</dd><dt>:as
<dd>
<p>Specifies a polymorphic interface (See <code>belongs_to</code>).</p>
</dd><dt>:through
<dd>
<p>Specifies an association through which to perform the query. This can be
any other type of association, including other <code>:through</code>
associations. Options for <code>:class_name</code>,
<code>:primary_key</code> and <code>:foreign_key</code> are ignored, as the
association uses the source reflection.</p>

<p>If the association on the join model is a <code>belongs_to</code>, the
collection can be modified and the records on the <code>:through</code>
model will be automatically created and removed as appropriate. Otherwise,
the collection is read-only, so you should manipulate the
<code>:through</code> association directly.</p>

<p>If you are going to modify the association (rather than just read from it),
then it is a good idea to set the <code>:inverse_of</code> option on the
source association on the join model. This allows associated records to be
built which will automatically create the appropriate join model records
when they are saved. (See the ‘Association Join Models’ section above.)</p>
</dd><dt>:source
<dd>
<p>Specifies the source association name used by <code>has_many
:through</code> queries. Only use it if the name cannot be inferred from
the association. <code>has_many :subscribers, :through =&gt;
:subscriptions</code> will look for either <code>:subscribers</code> or
<code>:subscriber</code> on Subscription, unless a <code>:source</code> is
given.</p>
</dd><dt>:source_type
<dd>
<p>Specifies type of the source association used by <code>has_many
:through</code> queries where the source association is a polymorphic
<code>belongs_to</code>.</p>
</dd><dt>:uniq
<dd>
<p>If true, duplicates will be omitted from the collection. Useful in
conjunction with <code>:through</code>.</p>
</dd><dt>:readonly
<dd>
<p>If true, all the associated objects are readonly through the association.</p>
</dd><dt>:validate
<dd>
<p>If <code>false</code>, don’t validate the associated objects when saving
the parent object. true by default.</p>
</dd><dt>:autosave
<dd>
<p>If true, always save the associated objects or destroy them if marked for
destruction, when saving the parent object. If false, never save or destroy
the associated objects. By default, only save associated objects that are
new records.</p>
</dd><dt>:inverse_of
<dd>
<p>Specifies the name of the <code>belongs_to</code> association on the
associated object that is the inverse of this <code>has_many</code>
association. Does not work in combination with <code>:through</code> or
<code>:as</code> options. See ActiveRecord::Associations::ClassMethods’s
overview on Bi-directional associations for more detail.</p>
</dd></dl>

<p>Option examples:</p>

<pre class="ruby"><span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">comments</span>, :<span class="ruby-identifier">order</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;posted_on&quot;</span>
<span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">comments</span>, :<span class="ruby-identifier">include</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">author</span>
<span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">people</span>, :<span class="ruby-identifier">class_name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;Person&quot;</span>, :<span class="ruby-identifier">conditions</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;deleted = 0&quot;</span>, :<span class="ruby-identifier">order</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;name&quot;</span>
<span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">tracks</span>, :<span class="ruby-identifier">order</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;position&quot;</span>, :<span class="ruby-identifier">dependent</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">destroy</span>
<span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">comments</span>, :<span class="ruby-identifier">dependent</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">nullify</span>
<span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">tags</span>, :<span class="ruby-identifier">as</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">taggable</span>
<span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">reports</span>, :<span class="ruby-identifier">readonly</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>
<span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">subscribers</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">subscriptions</span>, :<span class="ruby-identifier">source</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">user</span>
<span class="ruby-identifier">has_many</span> :<span class="ruby-identifier">subscribers</span>, :<span class="ruby-identifier">class_name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;Person&quot;</span>, :<span class="ruby-identifier">finder_sql</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-constant">Proc</span>.<span class="ruby-identifier">new</span> {
    <span class="ruby-node">%Q{
      SELECT DISTINCT *
      FROM people p, post_subscriptions ps
      WHERE ps.post_id = #{id} AND ps.person_id = p.id
      ORDER BY p.first_name
    }</span>
}
</pre>
          

          
          <div class="method-source-code" id="has_many-source">
            <pre><span class="ruby-comment"># File /usr/local/lib/ruby/gems/1.9.1/gems/activerecord-3.2.7/lib/active_record/associations.rb, line 1194</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">has_many</span>(<span class="ruby-identifier">name</span>, <span class="ruby-identifier">options</span> = {}, &amp;<span class="ruby-identifier">extension</span>)
  <span class="ruby-constant">Builder</span><span class="ruby-operator">::</span><span class="ruby-constant">HasMany</span>.<span class="ruby-identifier">build</span>(<span class="ruby-keyword">self</span>, <span class="ruby-identifier">name</span>, <span class="ruby-identifier">options</span>, &amp;<span class="ruby-identifier">extension</span>)
<span class="ruby-keyword">end</span></pre>
          </div><!-- has_many-source -->
          
        </div>

        

        
      </div><!-- has_many-method -->

    
      <div id="method-i-has_one" class="method-detail ">
        
        <div class="method-heading">
          <span class="method-name">has_one</span><span
            class="method-args">(name, options = {})</span>
          <span class="method-click-advice">click to toggle source</span>
        </div>
        

        <div class="method-description">
          
          <p>Specifies a one-to-one association with another class. This method should
only be used if the other class contains the foreign key. If the current
class contains the foreign key, then you should use <code>belongs_to</code>
instead. See also ActiveRecord::Associations::ClassMethods’s overview on
when to use <a href="ClassMethods.html#method-i-has_one">#has_one</a> and
when to use belongs_to.</p>

<p>The following methods for retrieval and query of a single associated object
will be added:</p>
<dl class="rdoc-list label-list"><dt>association(force_reload = false)
<dd>
<p>Returns the associated object. <code>nil</code> is returned if none is
found.</p>
</dd><dt>association=(associate)
<dd>
<p>Assigns the associate object, extracts the primary key, sets it as the
foreign key, and saves the associate object.</p>
</dd><dt>build_association(attributes = {})
<dd>
<p>Returns a new object of the associated type that has been instantiated with
<code>attributes</code> and linked to this object through a foreign key,
but has not yet been saved.</p>
</dd><dt>create_association(attributes = {})
<dd>
<p>Returns a new object of the associated type that has been instantiated with
<code>attributes</code>, linked to this object through a foreign key, and
that has already been saved (if it passed the validation).</p>
</dd><dt>create_association!(attributes = {})
<dd>
<p>Does the same as <code>create_association</code>, but raises
<code>ActiveRecord::RecordInvalid</code> if the record is invalid.</p>
</dd></dl>

<p>(<code>association</code> is replaced with the symbol passed as the first
argument, so <code>has_one :manager</code> would add among others
<code>manager.nil?</code>.)</p>

<h3 id="method-i-has_one-label-Example">Example</h3>

<p>An Account class declares <code>has_one :beneficiary</code>, which will
add:</p>
<ul><li>
<p><code>Account#beneficiary</code> (similar to
<code>Beneficiary.first(:conditions =&gt; &quot;account_id =
#{id}&quot;)</code>)</p>
</li><li>
<p><code>Account#beneficiary=(beneficiary)</code> (similar to
<code>beneficiary.account_id = account.id; beneficiary.save</code>)</p>
</li><li>
<p><code>Account#build_beneficiary</code> (similar to
<code>Beneficiary.new(&quot;account_id&quot; =&gt; id)</code>)</p>
</li><li>
<p><code>Account#create_beneficiary</code> (similar to <code>b =
Beneficiary.new(&quot;account_id&quot; =&gt; id); b.save; b</code>)</p>
</li><li>
<p><code>Account#create_beneficiary!</code> (similar to <code>b =
Beneficiary.new(&quot;account_id&quot; =&gt; id); b.save!; b</code>)</p>
</li></ul>

<h3 id="method-i-has_one-label-Options">Options</h3>

<p>The declaration can also include an options hash to specialize the behavior
of the association.</p>

<p>Options are:</p>
<dl class="rdoc-list label-list"><dt>:class_name
<dd>
<p>Specify the class name of the association. Use it only if that name can’t
be inferred from the association name. So <code>has_one :manager</code>
will by default be linked to the Manager class, but if the real class name
is Person, you’ll have to specify it with this option.</p>
</dd><dt>:conditions
<dd>
<p>Specify the conditions that the associated object must meet in order to be
included as a <code>WHERE</code> SQL fragment, such as <code>rank =
5</code>. Record creation from the association is scoped if a hash is used.
<code>has_one :account, :conditions =&gt; {:enabled =&gt; true}</code> will
create an enabled account with <code>@company.create_account</code> or
<code>@company.build_account</code>.</p>
</dd><dt>:order
<dd>
<p>Specify the order in which the associated objects are returned as an
<code>ORDER BY</code> SQL fragment, such as <code>last_name, first_name
DESC</code>.</p>
</dd><dt>:dependent
<dd>
<p>If set to <code>:destroy</code>, the associated object is destroyed when
this object is. If set to <code>:delete</code>, the associated object is
deleted <strong>without</strong> calling its destroy method. If set to
<code>:nullify</code>, the associated object’s foreign key is set to
<code>NULL</code>. Also, association is assigned. If set to
<code>:restrict</code> this object raises an
<code>ActiveRecord::DeleteRestrictionError</code> exception and cannot be
deleted if it has any associated object.</p>
</dd><dt>:foreign_key
<dd>
<p>Specify the foreign key used for the association. By default this is
guessed to be the name of this class in lower-case and “_id” suffixed. So a
Person class that makes a <code>has_one</code> association will use
“person_id” as the default <code>:foreign_key</code>.</p>
</dd><dt>:primary_key
<dd>
<p>Specify the method that returns the primary key used for the association.
By default this is <code>id</code>.</p>
</dd><dt>:include
<dd>
<p>Specify second-order associations that should be eager loaded when this
object is loaded.</p>
</dd><dt>:as
<dd>
<p>Specifies a polymorphic interface (See <code>belongs_to</code>).</p>
</dd><dt>:select
<dd>
<p>By default, this is <code>*</code> as in <code>SELECT * FROM</code>, but
can be changed if, for example, you want to do a join but not include the
joined columns. Do not forget to include the primary and foreign keys,
otherwise it will raise an error.</p>
</dd><dt>:through
<dd>
<p>Specifies a Join Model through which to perform the query. Options for
<code>:class_name</code>, <code>:primary_key</code>, and
<code>:foreign_key</code> are ignored, as the association uses the source
reflection. You can only use a <code>:through</code> query through a
<code>has_one</code> or <code>belongs_to</code> association on the join
model.</p>
</dd><dt>:source
<dd>
<p>Specifies the source association name used by <code>has_one :through</code>
queries. Only use it if the name cannot be inferred from the association.
<code>has_one :favorite, :through =&gt; :favorites</code> will look for a
<code>:favorite</code> on Favorite, unless a <code>:source</code> is given.</p>
</dd><dt>:source_type
<dd>
<p>Specifies type of the source association used by <code>has_one
:through</code> queries where the source association is a polymorphic
<code>belongs_to</code>.</p>
</dd><dt>:readonly
<dd>
<p>If true, the associated object is readonly through the association.</p>
</dd><dt>:validate
<dd>
<p>If <code>false</code>, don’t validate the associated object when saving the
parent object. <code>false</code> by default.</p>
</dd><dt>:autosave
<dd>
<p>If true, always save the associated object or destroy it if marked for
destruction, when saving the parent object. If false, never save or destroy
the associated object. By default, only save the associated object if it’s
a new record.</p>
</dd><dt>:inverse_of
<dd>
<p>Specifies the name of the <code>belongs_to</code> association on the
associated object that is the inverse of this <code>has_one</code>
association. Does not work in combination with <code>:through</code> or
<code>:as</code> options. See ActiveRecord::Associations::ClassMethods’s
overview on Bi-directional associations for more detail.</p>
</dd></dl>

<p>Option examples:</p>

<pre class="ruby"><span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">credit_card</span>, :<span class="ruby-identifier">dependent</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">destroy</span>  <span class="ruby-comment"># destroys the associated credit card</span>
<span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">credit_card</span>, :<span class="ruby-identifier">dependent</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">nullify</span>  <span class="ruby-comment"># updates the associated records foreign</span>
                                              <span class="ruby-comment"># key value to NULL rather than destroying it</span>
<span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">last_comment</span>, :<span class="ruby-identifier">class_name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;Comment&quot;</span>, :<span class="ruby-identifier">order</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;posted_on&quot;</span>
<span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">project_manager</span>, :<span class="ruby-identifier">class_name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;Person&quot;</span>, :<span class="ruby-identifier">conditions</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">&quot;role = 'project_manager'&quot;</span>
<span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">attachment</span>, :<span class="ruby-identifier">as</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">attachable</span>
<span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">boss</span>, :<span class="ruby-identifier">readonly</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-keyword">true</span>
<span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">club</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">membership</span>
<span class="ruby-identifier">has_one</span> :<span class="ruby-identifier">primary_address</span>, :<span class="ruby-identifier">through</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">addressables</span>, :<span class="ruby-identifier">conditions</span> =<span class="ruby-operator">&gt;</span> [<span class="ruby-string">&quot;addressable.primary = ?&quot;</span>, <span class="ruby-keyword">true</span>], :<span class="ruby-identifier">source</span> =<span class="ruby-operator">&gt;</span> :<span class="ruby-identifier">addressable</span>
</pre>
          

          
          <div class="method-source-code" id="has_one-source">
            <pre><span class="ruby-comment"># File /usr/local/lib/ruby/gems/1.9.1/gems/activerecord-3.2.7/lib/active_record/associations.rb, line 1308</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">has_one</span>(<span class="ruby-identifier">name</span>, <span class="ruby-identifier">options</span> = {})
  <span class="ruby-constant">Builder</span><span class="ruby-operator">::</span><span class="ruby-constant">HasOne</span>.<span class="ruby-identifier">build</span>(<span class="ruby-keyword">self</span>, <span class="ruby-identifier">name</span>, <span class="ruby-identifier">options</span>)
<span class="ruby-keyword">end</span></pre>
          </div><!-- has_one-source -->
          
        </div>

        

        
      </div><!-- has_one-method -->

    
    </section><!-- public-instance-method-details -->
  
  </section><!-- 5Buntitled-5D -->

</div><!-- documentation -->


<footer id="validator-badges">
  <p><a href="http://validator.w3.org/check/referer">[Validate]</a>
  <p>Generated by <a href="https://github.com/rdoc/rdoc">RDoc</a> 3.12.
  <p>Generated with the <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish Rdoc Generator</a> 3.
</footer>

